Java SE 8 Programmer I (OCAJP 8) study materials
Java SE 8 Programmer I (OCAJP 8) study resources

Java SE 8 Programmer I (OCAJP 8): Handling Exceptions

Java SE 8 Programmer I (OCAJP 8) · Work through your exam, one topic at a time.

All guide sections

Handling Exceptions

Handling Exceptions

This domain tests the exception hierarchy, checked versus unchecked exceptions, try/catch/finally, try-with-resources, and the throw and throws keywords. Expect questions on control flow and on which catch blocks compile.

Hierarchy and rules

  • Throwable splits into Error and Exception; RuntimeException is unchecked, while other Exception subclasses are checked. Checked exceptions must be caught or declared with throws.
  • catch blocks are tested in order; a superclass catch after a subclass catch is unreachable and fails to compile. Multi-catch (catch (IOException | SQLException e)) cannot include related types, and the variable is effectively final.
  • finally runs after try/catch on normal or exceptional exit, but not if the JVM exits via System.exit or crashes. A return in finally overrides earlier returns and exceptions.
  • Try-with-resources requires AutoCloseable resources; they close in reverse order, and close exceptions are suppressed.
  • throw throws one object; throws declares possible exceptions in a method signature. An overriding method may narrow checked exceptions but not add broader ones.

Worked example

public static void main(String[] args) {
  try {
    System.out.println("A");
    throw new RuntimeException();
  } catch (Exception e) {
    System.out.println("B");
  } finally {
    System.out.println("C");
  }
}

The try prints A, the exception is caught, B prints, and finally always runs, so C prints. Output is A B C on separate lines.

Traps

  • Catching Exception does not catch Error.
  • A checked exception thrown in a method without throws is a compile error even if callers catch it.
  • catch (Exception | RuntimeException e) is illegal because the alternatives are related.
  • Returning from finally can silently discard an exception.
  • A resource declared before the try is not automatically closed by try-with-resources.