我有几个(超过20个)方法(getXXX()
),它们在调用时可能会抛出异常(NotCalculatedException
)。重构调用其他方法的方法抛出异常
在另一种方法中,我需要访问这些方法给出的结果。就目前而言,我有一个可怕的代码,它看起来像:
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.");
}
...
}
,而无需修改getXXX
方法(因此他们必须保持自己的throws NotCalculatedException
),你会如何重构/简化myMethod()
使它看起来更好?
请注意,此项目仍在使用Java 1.4 :(
编辑
我不能把所有的getXXX()
方法在try { ... }
块,作为StringBuffer的意志如果一种方法抛出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.");
}
...
}
在其他也就是说,如果getFoo()
抛出一个NotCalculatedException
,我想有这样的输出:
foo = not calculated
bar = xxx
...
如果我把一切都放在一个单一的try { ... }
,我将有输出,我不想要得到:
foo = not calculated
是的,我想过使用反射,但我真的不喜欢这样的解决方案(在这种情况下)... – romaintaz 2009-09-15 14:33:01