Java SE 8 Programmer II study materials
Java SE 8 Programmer II study resources

Java SE 8 Programmer II: Exceptions and Assertions

Java SE 8 Programmer II · Work through your exam, one topic at a time.

All guide sections

Exceptions and Assertions

Exceptions and Assertions tests checked versus unchecked exceptions, resource management, custom exceptions, and the correct use of assertions.

Core rules

  • Throwable splits into Error (unrecoverable) and Exception. RuntimeException and its subclasses are unchecked; all other Exception subclasses are checked.
  • A checked exception must be caught or declared. Unchecked exceptions need not be.
  • try requires catch and/or finally; 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; or assert condition : detail;. They are disabled by default (-ea enables them), throw AssertionError, 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

  • finally runs even after return; a return in finally discards the original return value or exception.
  • Catching Exception before IOException makes the IOException catch unreachable.
  • Assertions are not for argument validation; they may be disabled in production.
  • A custom checked exception must extend Exception or a checked subclass; extending RuntimeException makes it unchecked.
  • Try-with-resources requires AutoCloseable; a class with only close() that does not implement it will not compile in that form.