Question

I need to trace through the following code. What happens? I got this far...

Let's start (now try f) F begins next throw Exc1 since var1 = false NOw do I return to try in main and go to method 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");
}
Was it helpful?

Solution

In this code:

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

If f() throws an exception, the try block will quit. Whether or not the exception is caught, main() will not call d(). If there's a catch block that catches the exception, it will be executed and then the finally block is executed; otherwise, the finally block is executed and then the exception is thrown again. But in both cases, d() will not be called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top