Card 09/ 10
All 10 cards
ExerciseDifficulty: Advanced1 min
Five Snippets: What Prints, and in What Order
Five short pieces. For each, write down everything printed and the order, or that it fails to compile. All five before the reveal.
// 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 is the one worth keeping. 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.