Card 09/ 10

ExerciseDifficulty: Advanced1 min

Practice: Predicting try, catch and finally Output

Five snippets: what prints and in what order, or that one fails to compile.

finally runs on every way out, the first matching catch wins, a wider catch above a narrower one does not compile, and a resource closes before finally. Using those rules, write down what each of the five snippets prints and in what order, or that it fails to compile, all five before opening the answer.

java
// 1
try { System.out.print("a"); throw new RuntimeException(); }
catch (RuntimeException e) { System.out.print("b"); }
finally { System.out.print("c"); }

// 2
try { return 1; } finally { System.out.print("d"); }

// 3
try { throw new IOException(); }
catch (IOException e) { System.out.print("e"); }
catch (Exception e) { System.out.print("f"); }

// 4
try { throw new IOException(); }
catch (Exception e) { System.out.print("g"); }
catch (IOException e) { System.out.print("h"); }

// 5
try (Scanner s = new Scanner("x")) { System.out.print("i"); }
finally { System.out.print("j"); }
The five results
Each snippet, what it does, and the rule behind it
SnippetResultRule
1abctry up to the throw, the matching catch, then finally
2d, then returns 1finally runs on every way out, including a return
3eFirst matching catch wins; the wider one is never reached
4Does not compileIOException is already covered by the Exception above it
5ijThe resource closes before finally, and closing prints nothing

Snippet four teaches the most. Ordering catch blocks from wide to narrow is a compile error rather than a silent problem, which is one of the few places Java refuses to let you write the unreachable version.