我想这不一定是'正确的'答案,也许它更像是一个风格问题,但我经常发现自己想知道如何构建try/catch块。嵌套式或顺序异常处理?
例如,采用下面我假设的一段代码(纯粹是说明性的)中概述的两种方法,我有一种方法会抛出我多次调用的异常,但需要根据调用它的不同处理方式。同样,不同的处理程序可能会引发不同类型的异常。
private Object exceptionMethod() throws Exception {
throw new Exception("Something bad happened");
}
public void useMethodSequentialHandlers() {
Object o1; // Must be declared in a wider scope than where it is used
try {
o1 = exceptionMethod();
} catch (Exception ex) {
// Assume we cannot continue after this exception so we'll return or
// rethrow to exit the method
return;
}
Object o2; // Must be declared in a wider scope than where it is used
// Do something that requires o1
for (int i = 0; i < 100; i++) {
try {
o2 = exceptionMethod();
// Here we would use the objects in some manner
boolean equal = o1.equals(o2);// Just a pointless example
// to show that both objects
// are required
// Assume the method does a load of stuff down here
} catch (Exception ex) {
// Assume we can continue to the next iteration after this exception
continue;
}
}
}
当我看到它有一个顺序的try/catch块的优点是,它是更清晰的读者正好在我回应异常哪一点因此,也许有更好的代码清晰。 缺点是我们在方法的各个地方散布了异常处理,而且我们的变量声明的范围比所需范围更广(这是一件坏事吗?)。
或者:
public void useMethodNestedHandlers() {
try {
Object o1 = exceptionMethod(); // Can be declared inside scope where it is used
// Do something that requires o1
for (int i = 0; i < 100; i++) {
try {
Object o2 = exceptionMethod(); // Can be declared inside scope where it is used
// Here we would use the objects in some manner
boolean equal = o1.equals(o2); // Just a pointless example
// to show that both objects
// are required
// Assume the method does a load of stuff down here
} catch (Exception ex) {
// Assume we can continue to the next iteration after this
// exception
continue;
}
}
} catch (Exception ex) {
// Assume we cannot continue after this exception so we'll return or
// rethrow to exit the method
return;
}
}
这里,我们使异常处理逻辑一起和变量的范围内声明他们正在使用。但是对我来说,异常处理逻辑似乎不太清晰,因为它远离了原点。 有没有人有意见哪一个会更好,或者我只是担心毫无意义的细节,应该继续工作? :-)
感谢
异常处理是花费时间的。 –
@SuzanCioc在规划和编码方面还是在执行方面?你在两个方面都是正确的,但我肯定会认同异常处理需要很多思考,有时甚至超过实际的正常业务逻辑流程。 – dassimon