为什么在try块中引发异常后的代码没有被执行?如果未处理异常,则控件熄灭?

时间:2017-01-07 09:39:32

标签: java exception try-catch try-catch-finally

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...");  
    }  
} 

1 个答案:

答案 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