jvm深度学习(15):JVM之异常处理机制try、catch、finally

JVM之异常处理机制

 

提问:异常在JVM是怎么处理的?

          如果写了try{}catch(){}finally{},又是怎么执行的?

 

代码的真理永远存在于字节码

 

show code1:

package com.imooc.firstappdemo.jvm;

public class TofuCaiExection {
    public static void main(String[] args) {
        int i = 0;
    }
}

反汇编:

主要看 红框内main函数,根据第三章节我们知道主要工作流程:1、将常量0加载到操作数栈;2、将常量0从操作数栈存入局部变量表;3;返回

 

show code2

package com.imooc.firstappdemo.jvm;

public class TofuCaiExection  {
    public static void main(String[] args) throws Exception {
        try {
            int i = 0;
        } catch (Exception e) {
            throw new Exception();
        }

    }
}

反汇编:

我们发现这次除了多了蓝色框区域Exception table异常表:意思是从(from)0行到(to)2行如果出现(type-Exception)异常则跳转(target)到第5条指令,执行catch中的代码指令。

 

show code3

package com.imooc.firstappdemo.jvm;

public class TofuCaiExection  {
    public static void main(String[] args) throws Exception {
        try {
            int i = 0;
        } catch (Exception e) {
            throw new Exception();
        }finally {
            int i = 9;
        }

    }
}

反汇编:

 我们发现特别有意思的是在异常表中,无论是try还是catch中都会跳到finally中,不仅如此,还在i=0之后直接执行了i=9

 

show code4

package com.imooc.firstappdemo.jvm;

public class TofuCaiExection  {
    public static void main(String[] args) throws Exception {
        try {
            int i = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            int i = 9;
        }

    }
}

反汇编:

我们发现个更有意思的情况,又多了一个i=9的操作,这个操作分别在try,catch,和finallly都存在。

总结:jvm在处理异常时try,catch和finally,通过异常表进行跳转操作。而在执行finally时,jvm为了保证这行代码一定执行,将finally中的代码指令有追加到try和catch后。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值