我想这不一定有一个“正确”的答案,也许这更像是一个风格问题,但我经常发现自己想知道如何构建 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;
}
}
在这里,我们将异常处理逻辑放在一起,变量在它们使用的范围内声明。但是对我来说,异常处理逻辑似乎不太清楚,因为它离起源点更远。有没有人认为哪个会更好,或者我只是担心毫无意义的细节,应该继续我的工作?:-)
谢谢