美文网首页
finally语句块一定会执行?

finally语句块一定会执行?

作者: 忘净空 | 来源:发表于2017-08-13 23:27 被阅读150次

简介

大家可能认为finally语句块一定会执行,我们总是将释放资源和关闭连接的代码放在finally语句块中,其实finally语句未必执行,下面看两个例子:

中止JVM(System.exit()命令)

public class Test {  
    public static void main(String[] args) {  
        try {  
            System.out.println("I'm nomal");  
            //0表示异常退出
            System.exit(0);  
        } catch (Exception ex) {  
            System.out.println("I'm exception");  
            System.exit(0);  
        } finally {  
            System.out.println("I'm finally.");  
        }  
    }  
}

备注:return不足以使finally语句块不执行,大家可以参考:finally块中的代码一定会执行吗?

Daemon线程中的finally语句块

public class Daemon {
    public static void main(String[] args) {
        Thread thread = new Thread(new DaemonRunner(), "DaemonRunner");
        thread.setDaemon(true);
        thread.start();
    }

    static class DaemonRunner implements Runnable {

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("DaemonRunner is finished");
            }
        }
    }
}

备注:Java中没有非守护线程后,虚拟机需要退出。虚拟机中的守护线程都要立即停止。

相关文章

网友评论

      本文标题:finally语句块一定会执行?

      本文链接:https://www.haomeiwen.com/subject/ughyrxtx.html