Card 09/ 10
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.
// 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
| Snippet | Result | Rule |
|---|---|---|
| 1 | abc | try up to the throw, the matching catch, then finally |
| 2 | d, then returns 1 | finally runs on every way out, including a return |
| 3 | e | First matching catch wins; the wider one is never reached |
| 4 | Does not compile | IOException is already covered by the Exception above it |
| 5 | ij | The 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.
← → move through sections and cards