猿问

为什么下面的Java代码的输出是“adb”,而不是“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”呢?


红颜莎娜
浏览 80回答 1
1回答

UYOU

str = "a"现在method1()被称为现在method2()被叫进来method1()nowmethod3()被调用method2() 并抛出异常,异常被捕获method2()并且str+= "c"不被执行。相反,会抛出一个新的异常并finally执行该子句:str += dmethod3() 再次被调用,抛出异常,该异常又被 method1() 添加捕获str += b我们到了。
随时随地看视频慕课网APP

相关分类

Java
我要回答