I have several (more than 20) methods (getXXX()
) that may throw an exception (a NotCalculatedException
) when they are called.
In another method, I need to access the results given by these methods. For the moment, I have an horrible code, which looks like:
public void myMethod() {
StringBuffer sb = new StringBuffer();
// Get 'foo' result...
sb.append("foo = ");
try {
sb.append(getFoo());
} catch (NotCalculatedException nce) {
sb.append("not calculated.");
}
// Get 'bar' result...
sb.append("\nbar = ");
try {
sb.append(getBar());
} catch (NotCalculatedException nce) {
sb.append("not calculated.");
}
...
}
Without modifying the getXXX
methods (thus they must keep their throws NotCalculatedException
), how would you refactor / simplify myMethod()
to make it looks better?
Please note that this project is still using Java 1.4 :(
EDIT
I cannot put all the getXXX()
methods in the try { ... }
block, as the StringBuffer will be incomplete if one method throws a NotCalculatedException
.
public void myMethod() {
StringBuffer sb = new StringBuffer();
try {
sb.append("foo = ");
sb.append(getFoo());
sb.append("\nbar = ");
sb.append(getBar());
} catch (NotCalculatedException nce) {
sb.append("not calculated.");
}
...
}
In others words, if getFoo()
throws a NotCalculatedException
, I want to have this kind of output :
foo = not calculated
bar = xxx
...
If I put everything in one single try { ... }
, I will have that output, which I don't want to get:
foo = not calculated