CAP477 · Unit 3: Exceptions and wrappers
Exception handling: try, catch, finally
8 practice questions
Key points
- Catch specific before general
- finally runs after return but not after System.exit
- Error is not an Exception
- Return in finally overrides
An exception is an event that disrupts normal flow. Java handles it with try { } catch (Type e) { } finally { }.
Hierarchy: Throwable -> Error (JVM problems such as StackOverflowError, OutOfMemoryError; do not catch) and Exception. Exception has checked exceptions (IOException, SQLException) and RuntimeException and its unchecked children (ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, NumberFormatException, IllegalArgumentException).
Flow rules (verified by running):
- The first matching
catchruns; later ones are skipped. Order catches from specific to general: a subclass catch after its superclass catch is a compile error ("has already been caught"). Multi-catchcatch (A | B e)is allowed for unrelated types. finallyruns whether or not an exception occurred, even after `return`. Exception: it does not run if the JVM exits (System.exit(0)).- A
returninsidefinallyoverrides an earlier return:try { return 1; } finally { return 2; }returns 2 (avoid it). But changing a local variable infinallyafterreturn xdoes not change the already-computed return value. trywithreturnprints:try,finally, then the caller prints1.- In
catch ... return s;withfinally { s += "c"; print }, the finally printsabcbut the method returns the earlierabvalue. - Nested: inner
finallyruns before the outercatch(f1,caught inner,f2).
Messages: Integer.parseInt("abc") -> NumberFormatException: For input string: "abc"; dividing integers by zero -> / by zero. StackOverflowError is an Error, not an Exception, so catch (Exception e) does not catch it.
Exam pitfall: a try block needs at least one catch or a finally (or resources).
Try two questions
Which of these is an unchecked exception?
- IOException
- SQLException
- Exception (the class itself)
- ArithmeticException
Show the answer
D. RuntimeException and its subclasses are unchecked.
Which statement about StackOverflowError is correct?
- It is a subclass of RuntimeException so it is unchecked
- It is an Error, so catch (Exception e) does not catch it
- It can never be caught by any catch block
- It is a checked exception that must be declared
Show the answer
B. Hierarchy check printed: true true false true (Exception, RuntimeException, Error-as-Exception, SOE-as-Error).