Exceptions

exercises
tutorial
java
exceptions

Applied class exercises for week 5, tracing execution through nested try/catch/finally blocks — reinforcing java-exceptions and 2026-03-19-exceptions. Two exception families are defined up front and used throughout. It helps to draw a diagram of the inheritance relationships between the classes, because every answer below turns on which class is a subclass of which.

class E1 extends Exception {};      class F1 extends Exception {};
class E2 extends E1 {};             class F2 extends F1 {};
class E3 extends E1 {};             class F3 extends F1 {};
class E4 extends E3 {};             class F4 extends F1 {};
class E5 extends E3 {};

Figure 1: The two exception families declared above. Two independent subtrees under Exception - no E is ever an F, which is why an F-typed catch clause can never claim an E and vice versa. E1 has two children and E3 two grandchildren; F1 has three children and no depth. Each connector ends in a single solid arrowhead at the parent’s bottom edge, so the arrows run from subclass to superclass.

Every one of these nine classes descends from Exception and none from RuntimeException, so all nine are checked exceptions — which is what makes the throws questions at the end of each exercise worth asking at all. The two rules the questions test are both readable off Figure 1:

  1. catch (T e) claims a thrown object if T is that object’s class or any ancestor of it — so a catch high in the tree swallows everything beneath it.
  2. catch clauses are tried in source order, and the first match wins. Order therefore matters whenever one clause’s type sits above another’s in the tree.

The code that follows is intended to illustrate concepts. Some details (for example, class declarations) are omitted. In all exercises, x and y are member variables.

On the HTML site, fill in each blank with your answer (as a quoted string, in the form x, y, e.g. "12, 20"), then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).

Question 1

x and y are member variables, both starting at 0:

int x = 0, y = 0;
public void exercise1() {
    try {
        try {
            f();
            y += 10;
        } catch (F3 e) {
            x += 1;
        } catch (F1 e) {
            x += 10;
        } catch (F4 e) {
            x += 100;
        } catch (E5 e) {
            y += 1;
            throw e;
        } finally {
            x += 2;
        }
        y += 20;
    } catch (Exception e) {
        y += 100;
    }
}

What are x, y after exercise1() is called, if f() throws each of the following?

f() throws F2 →

f() throws F3 →

f() throws F4 →

f() throws E4 →

f() throws E5 →

Figure 2: Exercise 1’s structure with each thrown type routed to the clause that actually claims it, and the outcome labelled beside each clause. The three things to read off it: catch (F1) sits above catch (F4) in source order and so claims F4 before that clause is ever reached; finally runs on every one of the five paths; and the two throws that leave the inner try - the unmatched E4 and the rethrown E5 - are the ones that skip y += 20 on the way to the outer handler.

  • F2 → not F3, not F4, not E5, but is an F1 (F2 extends F1), so catch (F1 e): x += 10. finally always runs: x += 2 → x = 12. Nothing escapes the inner try, so y += 20 still runs → y = 20.
  • F3 → matched directly by catch (F3 e): x += 1; finally: x += 2 → x = 3; y += 20 runs → y = 20.
  • F4 → this is the ordering trap. catch (F1 e) comes first in source order and F4 extends F1, so the F1 clause claims it and catch (F4 e) never runs: x += 10, finally x += 2 → x = 12, y += 20 → y = 20. Identical to the F2 answer, for the same reason.
  • E4 → nothing in the inner try matches. F3/F1/F4 are the other family entirely, and E5 is E4’s sibling, not an ancestor (both hang off E3). Only finally runs — x += 2 → x = 2 — and the exception keeps propagating, skipping y += 20, into catch (Exception e): y += 100 → y = 100.
  • E5 → matched by catch (E5 e): y += 1, then re-thrown. finally still runs on the way out: x += 2 → x = 2. The rethrow escapes the inner try entirely (so y += 20 is skipped — a rethrow from a catch is not offered to that same try’s other clauses) and lands in the outer catch (Exception e): y += 100 → y = 1 + 100 = 101.

Does exercise1 need a throws declaration? No. All the exceptions thrown by f() are caught either by the inner try or by the outer try, and the re-thrown exception is caught by the outer try. If all thrown exceptions are handled by a try/catch then a throws declaration is not required. The outer catch (Exception e) is what guarantees this — it sits at the root of Figure 1 and therefore claims anything at all.

CautionThis exercise would not compile as written

The exercise is a paper trace only. catch (F1 e) followed by catch (F4 e) is a compile-time error in Java, not merely a dead branch — javac reports “exception F4 has already been caught” whenever a preceding clause’s type is a superclass of a later clause’s. So the F4 answer is testing the rule (first matching clause wins, subclasses must be caught before superclasses) rather than describing code you could run. The same reasoning is what makes catch (Exception e) legal only as the last clause of a chain.

Question 2 — bonus

int x = 0, y = 0;
public void exercise2() throws ... {
    try {
        y += g();
    } catch (E3 e) {
        x += 100;
    }
}

public int g() throws ... {
    try {
        f();
        y += 10;
        return 400;
    } catch (E1 e) {
        x += 1;
    } finally {
        x += 10;
    }
    return 1;
}

f() throws E1 →

f() throws E2 →

f() throws E3 →

All three inputs give the same answer, x = 11, y = 1, and the reason is one line of Figure 1: E1, E2 and E3 all sit at or below E1, so g’s single catch (E1 e) claims every one of them.

Tracing g() for any of the three:

  1. f() throws, so y += 10 and return 400 are both skipped.
  2. catch (E1 e) runs: x += 1 → x = 1.
  3. finally runs: x += 10 → x = 11.
  4. Control leaves the try/catch/finally normally — the catch body has no return of its own — and reaches return 1. So g() returns 1.
  5. Back in exercise2, y += g() adds that 1 → y = 1. No exception ever escapes g, so exercise2’s catch (E3 e) never runs and x stays at 11, not 111.

The return 400 inside the try is the trap: it looks like the method’s answer but it is unreachable on every path where f() throws. On the path where f() does not throw, y += 10 runs, return 400 is evaluated, finally still executes x += 10 before the value leaves the method, and exercise2 ends at x = 10, y = 410 — finally runs on a return just as it does on a throw.

The throws declarations for the methods exercise2 and g would be different, depending on which type of exception f() is throwing. That is why both signatures are written as throws ... — the declaration is a function of f’s, and f’s is deliberately left unspecified.

Question 3 — bonus

g() throws F2 (unconditionally, when called):

int x = 0, y = 0;
public void exercise3() throws ... {
    try {
        try {
            try {
                f();
                x += 100;
            } catch (F2 e) {
                x += 5;
                g();
            } catch (F1 e) {
                x += 1;
            } catch (E1 e) {
                y += 2;
                throw e;
            }
            y += 10;
        } catch (F2 f) {
            y += 100;
        }
    } catch (Exception e) {
        x += 1000;
    }
}

f() throws F3 →

f() throws F2 →

f() throws E1 →

f() throws F1 →

x += 100 sits inside the innermost try, immediately after f() — so on every one of these four inputs it is skipped.

  • F3 → catch (F2 e) does not match (F3 is F2’s sibling, not its descendant); catch (F1 e) does: x += 1. Nothing further is thrown, so y += 10 runs and neither outer handler fires → x = 1, y = 10.
  • F2 → catch (F2 e) matches: x += 5, then it calls g(), which throws F2. A throw from inside a catch body is not offered to that same try’s remaining clauses — it propagates outward. It skips y += 10 and lands in the middle catch (F2 f): y += 100 → x = 5, y = 100.
  • E1 → neither F clause matches, catch (E1 e) does: y += 2, then rethrows. An E1 is not an F2, so the middle handler passes; the outermost catch (Exception e) claims it: x += 1000 → x = 1000, y = 2.
  • F1 → an F1 is not an F2 (the subclass relation only runs downward), so the first clause passes and catch (F1 e) takes it: x += 1, y += 10 runs → x = 1, y = 10. Same answer as F3, because both reach the same handler.

The pair of F2 cases is the one to take away: throwing F2 into a try whose own first clause is catch (F2 e) gets caught there, but throwing F2 from inside that clause escapes to the next try out. Two identical exception types, two completely different destinations, decided by where the throw happens rather than what is thrown.