简体   繁体   English

Java在`finally`块之后不打印消息

[英]Java not printing messages after `finally` block

This question relates to the finally blocks in Java. 这个问题与Java中的finally块有关。 Here "rest of the code" is not printing, which is after the finally block. 在此处,“代码的其余部分”不是打印出来的,而是在finally块之后。

But when an exception is not there then it will print whatever is after the finally block. 但是,当不存在异常时,它将在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...");  
    }  
}  

Because you was not catching java.lang.ArithmeticException and code gets terminated at that point. 因为您没有捕获java.lang.ArithmeticException,并且代码在那一刻被终止。

Try this: 尝试这个:

class TestFinallyBlock1 {
    public static void main(String args[]) {
        try {
            int data = 25 / 0;
            System.out.println(data);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            System.out.println("finally block is always executed");
        }
        System.out.println("rest of the code...");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM