我试图了解下面的异常代码在运行时打印的内容。我知道它打印的是什么“adb”,但我不明白为什么要打印它。public class MyClass {static String str = "a";public static void main(String[] args) { new MyClass().method1(); System.out.println(str);}void method1() { try { method2(); } catch (Exception e) { str += "b"; }}void method2() throws Exception { try { method3(); str += "c"; } catch (Exception e) { throw new Exception(); } finally { str += "d"; } method3(); str += "e";}void method3() throws Exception { throw new Exception();}}当调用method3()时,它抛出一个新的异常,该异常被method2()捕获,同样抛出一个新的异常,该异常被method1()捕获,在字符串中添加“b”,然后在finally块中执行method2(),添加“d”?那么为什么不是“abd”,而是“adb”呢?
1 回答
UYOU
TA贡献1878条经验 获得超4个赞
str = "a"
现在method1()
被称为
现在method2()
被叫进来method1()
nowmethod3()
被调用method2()
并抛出异常,异常被捕获method2()
并且str+= "c"
不被执行。相反,会抛出一个新的异常并finally
执行该子句:
str += d
method3() 再次被调用,抛出异常,该异常又被 method1() 添加捕获
str += b
我们到了。
添加回答
举报
0/150
提交
取消