It is important to pay attention to the declaration at the top.
static class ExceptionA extends RuntimeException { }
static class ExceptionB extends ExceptionA { }
static class ExceptionC extends RuntimeException { }
static 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+2;
}
}
public static int foo(int y) {
int x = 0;
try {
x += bar(y);
x += 1;
} catch (ExceptionA e1) {
try {
x += bar(y*2);
}
catch (ExceptionB e2) {
x += 2;
}
x += 2;
} catch (ExceptionC e1) {
x += 3;
} catch (RuntimeException e1) {
x += 4;
} finally {
x += 1;
}
return x;
}
}
Split your windows so you can follow along with the code.
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 first try block. Trying to call bar(2)
This falls in the second case: throw ExceptionB -> ExceptionA
Inside ExceptionB try block. Increasing x from 0 to 2
Inside ExceptionA at the end. Increasing x from 2 to 4
Finally. Increasing x from 4 to 5
final = 5
foo(2);
Inside first try block. Trying to call bar(2)
This falls in the second case: throw ExceptionB -> ExceptionA
Caught an ExceptionA
Inside ExceptionA first try block. Trying to call bar(4)
This falls in the fourth case: throw ExceptionD -> ExceptionB -> ExceptionA -> RuntimeException
Inside ExceptionB try block. Increasing x from 0 to 2
Inside ExceptionA at the end. Increasing x from 2 to 4
Finally. Increasing x from 4 to 5
final = 5
foo(3);
Inside first try block. Trying to call bar(3)
This falls in the third case: throw ExceptionC -> RuntimeException
Caught an ExceptionC. Increasing x from 0 to 3
Finally. Increasing x from 3 to 4
final = 4
foo(4);
Inside first try block. Trying to call bar(4)
This falls in the fourth case: throw ExceptionD -> ExceptionB -> ExceptionA -> RuntimeException
Caught an ExceptionA
Inside ExceptionA first try block. Trying to call bar(8)
returning the value 10
calling bar(8) did not result in error. Increase x to 10
Inside ExceptionA at the end. Increasing x from 10 to 12
Finally. Increasing x from 12 to 13
final = 13
foo(5);
Inside first try block. Trying to call bar(5)
returning the value 7
calling bar(5) did not result in error. Increase x to 7, then by 1
Finally. Increasing x from 8 to 9
final = 9