1Z0-771 study materials
1Z0-771 study resources

1Z0-771: Controlling Program Flow and Exception Handling

1Z0-771 · Work through your exam, one topic at a time.

All guide sections

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

  • if requires a boolean; Java has no integer truthiness.
  • switch works on int-compatible types, String, or enum. case labels must be compile-time constants and unique; without break, return or throw, execution falls through.
  • do-while runs its body at least once. Labels let break label; and continue label; target an outer loop.

Exceptions

  • Throwable splits into Error and Exception; RuntimeException and subtypes are unchecked, everything else under Exception is checked.
  • Checked exceptions must be caught or declared. catch blocks must run from subtype to supertype; an unreachable catch is a compile error.
  • Multi-catch catch (IOException | SQLException e) makes e effectively final.
  • finally runs even after return, but not after System.exit or a JVM crash. A return inside finally discards 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 before catch (IOException e) does not compile.
  • An overriding method may narrow checked exceptions but never widen them.
  • A finally block that throws hides the original exception.
  • case fall-through and missing default are the most common loop/switch logic errors.