Java SE 11 Developer study materials
Java SE 11 Developer study resources

Java SE 11 Developer: Exception Handling and Assertions

Java SE 11 Developer · Work through your exam, one topic at a time.

All guide sections

Exception Handling and Assertions

This domain tests the checked/unchecked split, try-with-resources semantics, and when assertions actually execute.

Checked, unchecked and Error

Throwable splits into Error (JVM problems - do not catch) and Exception. RuntimeException and its subclasses are unchecked; everything else under Exception is checked and must be caught or declared with throws. Catch blocks are examined in order, so a supertype before a subtype will not compile. Multi-catch, catch (IOException | SQLException e), makes e effectively final, and the alternatives may not be related by subclassing.

try-with-resources

Resources must be AutoCloseable and are closed in reverse declaration order. A variable can be reused if it is effectively final (Java 9+). If the body throws and close also throws, the body exception propagates and the close exception is attached via getSuppressed(). finally always runs except after System.exit or a JVM crash, and a return inside finally silently discards any earlier return value.

Assertions

Disabled by default at runtime; enable with -ea, or per package with -ea:com.acme.... A failed assertion throws AssertionError, which is an Error and normally not caught. The detail expression is evaluated only when the assertion fails. Assertions suit internal invariants, never public-API argument validation, because production runs with them off.

Custom exceptions

Extend Exception for a recoverable, checked condition and RuntimeException for programming errors. Preserve the cause with super(message, cause).

Worked example

A resource whose close() throws while the body throws IllegalStateException: the caller sees IllegalStateException and e.getSuppressed()[0] is the close failure. Reasoning: try-with-resources never hides the primary failure.

Traps

Catching Exception and swallowing it; declaring a broader checked exception in an override (illegal); finally overriding a return; assuming assertions run by default.