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...");
}
}
答案 0 :(得分:0)
我认为如果你提取方法并添加额外的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 Language Specification - Execution of try-finally and try-catch-finally