异常处理Try-catch:如果var 1,2和3为false,会发生什么

时间:2014-02-14 20:16:46

标签: java exception exception-handling try-catch runtime-error

我需要跟踪以下代码。怎么了? 我到目前为止......

让我们开始吧(现在试试f) F开始下一次抛出Exc1,因为var1 = false 我是否会返回主要尝试并转到方法d?

void main() {
    println("Let's start");
    try {
        f();
        d();
    } catch (Ex1 ex) {
        println("main caught Ex1");
    } catch (Ex3 ex) {
        println("main caught Ex3");
    } finally {
        println("main finally");
    }
    println("main end");
}

void f() {
    println("F begins");
    try {
        if (var1) {
            d();
        } else {
            throw new Ex1();
        }
    } catch (Ex2 ex) {
        println("f caught Ex2");
    }
    println("a end");
}

void d() {
    println("d begin");
    try {
        if (var2) throw new Ex2();
        if (var3) throw new Ex3();
    } catch (Ex3 ex) {
        println("d caught ex3");
    } finally {
        println("d finally");
    }
    println("d end");
}

1 个答案:

答案 0 :(得分:1)

在此代码中:

try {
    f();
    d();
} catch (Ex1 ex) {
    println("main caught Ex1");
} catch (Ex3 ex) {
    println("main caught Ex3");
} finally {
    println("main finally");
}

如果f()抛出异常,try块将退出。无论是否捕获到异常,main()都会致电d()。如果有一个catch块捕获异常,它将被执行,然后执行finally块;否则,执行finally块,然后再次抛出异常。但在这两种情况下,都不会调用d()