class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
我认为如果您提取方法并添加额外的 try-catch 块,您可以理解该行为,如下所示:
public class TestFinallyBlock1 {
public static void main(String args[]) {
try {
throwArithmeticException();
System.out.println("rest of the code...");
} catch (ArithmeticException e) {
System.out.println(e);
}
}
private static void throwArithmeticException() {
try {
int data = 25 / 0;
System.out.println(data);
} catch (NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
}
}
有关更多详细信息,请参阅 Java 语言规范 - 执行 try-finally 和 try-catch-finally