Card 09/ 10

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.

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 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.