to problem set

Problem 12 - Exceptions

class ExceptionA extends RuntimeException {}
class ExceptionB extends ExceptionA {}
class ExceptionC extends ExceptionA {}
class ExceptionD extends ExceptionB {}
public static int bar(int x) {
    switch (x) {
        case 1:
            throw new ExceptionA();
        case 2:
            throw new ExceptionB();
        case 3:
            throw new ExceptionC();
        case 4:
            throw new ExceptionD();
        default:
            return x*x;
    }
}
public static int foo(int y) {
    int x = 0;
    try {
        try {
            x += bar(y);
        } catch (ExceptionD ex_d) {
            x = -3;
        } catch (ExceptionC ex_c) {
            x += bar(y-1);
        } catch (ExceptionA ex_a) {
            try {
                x += bar(y+3);
            } catch (ExceptionB ex_b) {
                x += 3;
            }
            finally {
                x += 3;
            }
        }
    } catch (RuntimeException e) {
        x += 5;
    } finally {
        x += 3;
    }
    return x;
}

Following along with the text in a separate window to see the code flow.
foo(1);

Inside first try block. Trying to call bar(1)
This falls in the first case: throw ExceptionA -> RuntimeException
Caught an ExceptionA
Inside ExceptionA try. Calling bar(4)
This falls in the first case: throw ExceptionD -> ExceptionB -> ExceptionA -> RuntimeException
Caught an ExceptionB
Adding 3 to x. x goes from 0 to 3
Inside the finally block of ExceptionA try block. Increasing x from 3 to 6
Inside the last finally block. Increasing x from 6 to 9

Final value: 9

foo(2);

Inside first try block. Trying to call bar(2)
This falls in the first case: throw ExceptionB -> ExceptionA -> RuntimeException
Caught an ExceptionA
Inside ExceptionA try. Calling bar(5)
returning the value 25
calling bar(5) did not result in error. Increasing x from 0 to 25
returning the value 25
Inside the finally block of ExceptionA try block. Increasing x from 25 to 28
Inside the last finally block. Increasing x from 28 to 31

Final value: 31

foo(3);

Inside first try block. Trying to call bar(3)
This falls in the first case: throw ExceptionC -> ExceptionA -> RuntimeException
Caught an ExceptionC
Trying to call bar(2)
This falls in the first case: throw ExceptionB -> ExceptionA -> RuntimeException
Caught a RuntimeException of the very first try block
Increasing x from 0 to 5
Inside the last finally block. Increasing x from 5 to 8

Final value: 8

foo(4);

Inside first try block. Trying to call bar(4)
This falls in the first case: throw ExceptionD -> ExceptionB -> ExceptionA -> RuntimeException
Caught an ExceptionD
Decreasing x from 0 to -3
Inside the last finally block. Increasing x from -3 to 0

Final value: 0

foo(5);

Inside first try block. Trying to call bar(5)
returning the value 25
calling bar(5) did not result in error. Increasing x from 0 to 25
Inside the last finally block. Increasing x from 25 to 28

Final value: 28