beginnerFree

Exception Handling

try / catch / finally - handle errors gracefully

Exception Handling

Checked exceptions must be caught or declared. Unchecked are runtime errors. Finally normally runs after try/catch (only a hard exit like System.exit skips it).

The narrated version of this skribble — tap play for the full-size video.

0:00 / 1:27

The Big Picture

Exceptions handle runtime errors without crashing the program. When something goes wrong, Java throws an exception object that travels up the call stack until caught.

  • Checked exceptions must be declared or caught
  • Unchecked exceptions (runtime) don't require handling
  • try/catch/finally is the core mechanism

How It Works

When thrown, the JVM unwinds the stack looking for a match.

  • try blocks contain risky code
  • catch handles specific exception types
  • finally normally runs after try/catch (cleanup resources)
  • Checked: IOException must be caught or declared throws
  • Unchecked: NullPointerException extends RuntimeException

In the Java Landscape

Java 7+ try-with-resources auto-closes AutoCloseable objects.

  • Multi-catch: catch (IOException | SQLException e)
  • Suppressed exceptions accessible via getSuppressed()
  • Optional (Java 8) reduces null-related exceptions
  • Helpful NPE messages added in Java 14
  • Pattern matching reduces ClassCastException risk

Pitfalls and Best Practices

  • Catch specific types; broad Exception only at boundaries, never Throwable
  • Don't swallow exceptions - always log or rethrow
  • Avoid exceptions for control flow (expensive stack traces)
  • Include context in messages: what failed and why
  • Use unchecked for bugs, checked for recoverable issues
  • Prefer try-with-resources over manual finally blocks
#java#exceptions