提问:异常在JVM是怎么处理的?
如果写了try{}catch(){}finally{},又是怎么执行的?
代码的真理永远存在于字节码
package com.imooc.firstappdemo.jvm;
public class TofuCaiExection {
public static void main(String[] args) {
int i = 0;
}
}
反汇编:
主要看 红框内main函数,根据第三章节我们知道主要工作流程:1、将常量0加载到操作数栈;2、将常量0从操作数栈存入局部变量表;3;返回
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中的代码指令。
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
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后。