这是 Oracle-Certified-Professiona-Java-SE-8-Programmer-Exam-1Z0-809 一书中的引述
在 try-with-resources 语句中,可能会抛出多个异常;例如,一个在 try 块中,一个在 catch 块中,另一个在 finally 块中。但是,只能捕获一个异常,因此其他异常将被列为抑制异常。从给定的异常对象中,您可以使用 getSuppressed() 方法来获取被抑制的异常列表。
我在实践中尝试过:
System.out.println("Type an integer in the console: ");
try(Scanner consoleScanner = new Scanner(System.in)) {
System.out.println("You typed the integer value: " + consoleScanner.nextInt());
int kil = 8/0;
} catch(Exception e) {
// catch all other exceptions here ...
System.out.println("Error: Encountered an exception and could not read an integer from the console... ");
System.out.println("Exiting the program - restart and try the program again!");
}finally {
int kil = 8/0;
}
结果一点也不奇怪:
Type an integer in the console:
5
You typed the integer value: 5
Error: Encountered an exception and could not read an integer from the console...
Exiting the program - restart and try the program again!
Exception in thread "main" java.lang.ArithmeticException: / by zero
at package3.MethodReference.main(MethodReference.java:183)
没有抑制发生。还是正在发生?那么如何理解异常输出到控制台呢?还是我误会了什么?
您的代码中不需要抑制。你捕获一个异常,记录它,在那一刻它被认为是已处理的,然后控制权被转移到 finally 并在那里抛出一个新的异常。
拆下捕捉部分并捕捉到上面的水平。在这种情况下,finally 部分将抛出一个新的异常,而堆栈上已经有一个未处理的异常 - 这就是抑制发生的时刻。