为什么 Java 代码的输出低于 "adb",而不是 "abd"?
Why is the output of the Java code below "adb", and not "abd"?
我想了解以下异常代码在 运行 时打印的内容。我知道它打印什么,"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"呢?
str = "a"
现在 method1()
被调用
现在 method2()
在 method1()
中调用
现在 method3()
在 method2()
中调用
并抛出异常,异常在method2()
被捕获,str+= "c"
没有执行。而是抛出一个新的异常并执行 finally
子句:
str += d
method3() 再次调用,抛出异常,该异常又被 method1() 添加
str += b
我们到了。
我想了解以下异常代码在 运行 时打印的内容。我知道它打印什么,"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"呢?
str = "a"
现在 method1()
被调用
现在 method2()
在 method1()
现在 method3()
在 method2()
中调用
并抛出异常,异常在method2()
被捕获,str+= "c"
没有执行。而是抛出一个新的异常并执行 finally
子句:
str += d
method3() 再次调用,抛出异常,该异常又被 method1() 添加
str += b
我们到了。