考虑一下我在面试中被问到的这个问题
public class Test_finally {
private static int run(int input) {
int result = 0;
try {
result = 3 / input;
} catch (Exception e) {
System.out.println("UnsupportedOperationException");
throw new UnsupportedOperationException("first");
} finally {
System.out.println("finally input=" + input);
if (0 == input) {
System.out.println("ArithmeticException");
throw new ArithmeticException("second");
}
}
System.out.println("end of method");
return result * 2;
}
public static void main(String[] args) {
int output = Test_finally.run(0);
System.out.println(" output=" + output);
}
}
此程序的输出抛出ArithmeticException
而不是UnsupportedOperationException
面试官只是问我如何让客户知道最初提出的异常类型是UnsupportedOperationException
而不是ArithmeticException
。我不知道
永远不要返回或抛出finally块。作为一个面试官,我希望得到这样的答案。
一个蹩脚的面试官在寻找一个小的技术细节时可能会期望你知道Exception.addSuppressed()
。你实际上不能在finally块中读取抛出的异常,所以你需要将它存储在throw块中以重用它。
就像这样:
private static int run(int input) throws Exception {
int result = 0;
Exception thrownException = null;
try {
result = 3 / input;
} catch (Exception e) {
System.out.println("UnsupportedOperationException");
thrownException = new UnsupportedOperationException("first");
throw thrownException;
} finally {
try {
System.out.println("finally input=" + input);
if (0 == input) {
System.out.println("ArithmeticException");
throw new ArithmeticException("second");
}
} catch (Exception e) {
// Depending on what the more important exception is,
// you could also suppress thrownException and always throw e
if (thrownException != null){
thrownException.addSuppressed(e);
} else {
throw e;
}
}
}
System.out.println("end of method");
return result * 2;
}