try {
throw new RuntimeException();
} catch (Exception e) {
System.out.println("catch");
throw new RuntimeException();
} finally {
System.out.println("finally");
}
异常处理中,有finally的话都会最后执行finally中的语句块,执行结果为
catch
finally
Exception in thread "main" java.lang.RuntimeException at FileMapper.main(FileMapper.java:26)
从结果看到其实是先执行了catch中的语句块,就是说先执行了throw new RuntimeException();
一般情况下没有 finally的话,程序就直接中断了。jvm是怎么保证如果有finally的话,先执行一下finally中的语句再抛出异常呢?
因为看输出,其实throw new RuntimeException(); 是在前面执行的。
finally是在try语句中最后执行。
你的代码的意思是。
在try的时候抛出一个RuntimeException(既然抛出了,在try里就不做处理),然后try里的代码执行完了,接着执行finally中的代码,这个try语句就彻底执行完了。
接着该执行try以外的代码了,发现一个RuntimeException没有处理,故报了异常Exception in thread "main" java.lang.RuntimeException at FileMapper.main(FileMapper.java:26)
catch语句块中throw new RuntimeException()的时候,为啥没有第一时间吧异常跑出去,而是执行完了finally 中的代码 再抛出。如果先执行了finally 中代码再执行catch中的代码,这样就好理解了。但是从打印出的东西看,又不是这样。