try, catch and finally Flow Puzzles
40 min · Intermediate
A finally block runs after try and catch whether they finish normally, return or throw. Exception puzzles test exactly when it runs, which return value wins, and which exception survives when more than one is thrown.
Topics in this lesson
- return in try and finally: which value wins
- finally changing a returned primitive vs an object
- Exceptions thrown in catch and in finally: what is lost
- Nested try blocks and which catch runs
- Unreachable catch blocks: compile errors
Interview questions this lesson answers
- What prints for
try { throw new RuntimeException(); } catch (RuntimeException e) { System.out.print("C"); } finally { System.out.print("F"); } System.out.print("E");? - What prints for
try { System.exit(0); } finally { System.out.print("F"); }? - If try has return 1 and finally prints something, what happens?
- What happens if both try and finally return a value?
- Why is returning from finally a bad idea?
- Can finally change the value returned from try?
- What happens if finally throws an exception?
- What happens if catch throws an exception?
- In try-with-resources, if the body throws and
close()also throws, which exception reaches the catch? - For
throw new RuntimeException("wrap", new IOException("disk")), what doese.getCause().getMessage()give?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.