Controlling Program Flow and Exception Handling
Domain 2 covers branching, loops, and the checked/unchecked exception model: which catch blocks are reachable, when finally runs, and how try-with-resources closes resources.
Control flow
ifrequires aboolean; Java has no integer truthiness.switchworks onint-compatible types,String, or enum.caselabels must be compile-time constants and unique; withoutbreak,returnorthrow, execution falls through.do-whileruns its body at least once. Labels letbreak label;andcontinue label;target an outer loop.
Exceptions
Throwablesplits intoErrorandException;RuntimeExceptionand subtypes are unchecked, everything else underExceptionis checked.- Checked exceptions must be caught or declared.
catchblocks must run from subtype to supertype; an unreachable catch is a compile error. - Multi-catch
catch (IOException | SQLException e)makeseeffectively final. finallyruns even afterreturn, but not afterSystem.exitor a JVM crash. Areturninsidefinallydiscards the pending return value.
try-with-resources
Resources must implement AutoCloseable and are closed in reverse declaration order. A close failure is attached as a suppressed exception to the primary one and retrieved with getSuppressed().
Worked example
try (var r = new Res()) { // Res implements AutoCloseable
throw new RuntimeException("body");
} catch (Exception e) {
System.out.println(e.getMessage());
}
close() runs before the catch block is entered, so a failure in close() becomes suppressed on the body exception rather than replacing it.
Traps
catch (Exception e)placed beforecatch (IOException e)does not compile.- An overriding method may narrow checked exceptions but never widen them.
- A
finallyblock that throws hides the original exception. casefall-through and missingdefaultare the most common loop/switch logic errors.