Exceptions and Assertions
Exceptions and Assertions tests checked versus unchecked exceptions, resource management, custom exceptions, and the correct use of assertions.
Core rules
Throwablesplits intoError(unrecoverable) andException.RuntimeExceptionand its subclasses are unchecked; all otherExceptionsubclasses are checked.- A checked exception must be caught or declared. Unchecked exceptions need not be.
tryrequirescatchand/orfinally; multi-catch uses|and the parameter is implicitly final. Catch blocks must be ordered from most specific to most general.- Try-with-resources closes resources in reverse order of declaration; close failures are added as suppressed exceptions.
- An overriding method may declare fewer or narrower checked exceptions, never broader ones.
- Assertions use
assert condition;orassert condition : detail;. They are disabled by default (-eaenables them), throwAssertionError, and must not perform business logic or validation.
Worked example
try (Reader r = new FileReader("a.txt"); Reader s = new FileReader("b.txt")) { ... }
s closes first, then r. If the body throws and s.close() also throws, the body exception propagates and the close exception is attached via getSuppressed().
Traps
finallyruns even afterreturn; areturninfinallydiscards the original return value or exception.- Catching
ExceptionbeforeIOExceptionmakes theIOExceptioncatch unreachable. - Assertions are not for argument validation; they may be disabled in production.
- A custom checked exception must extend
Exceptionor a checked subclass; extendingRuntimeExceptionmakes it unchecked. - Try-with-resources requires
AutoCloseable; a class with onlyclose()that does not implement it will not compile in that form.