Java异常-finally

为什么finally语句块一定能得到执行?
其实编译器做了个冗余,比如我们写的是这样:

public class Demo {
    public static void main(String[] args) {
        try {
            foo();
        } catch (IOException e) {
            int a = 100;
        } catch (Exception e) {
            int b = 200;
        } finally {
            int c = 300;
        }
    }

    public static void foo() throws IOException {

    }
}

但我们看字节码的时候会发现,好几个地方都有int c = 300的字节码,那我们再反编译一下,得到如下:

public static void main(String[] args) {
        try {
            foo();
            int c = 300; // 冗余
        } catch (IOException e) {
            int a = 100;

            int c = 300; // 冗余
        } catch (Exception e) {
            int b = 200;

            int c = 300; // 冗余
        } finally {
            int c = 300;
        }
}

所以写代码的时候,如果我们在finally里放太多,会导致字节码条数增加很多的。

但是,finally在某些情况下,是不会执行的

(1)在try块前就返回了,因为没触发try,所以更不可能碰到finally了;

(2)try块里放了System.exit(0),它是什么,它可是直接终止JVM的呀,整个JVM哦豁了。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章