beginnerFree
Exception Handling
try / catch / finally - handle errors gracefully

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).
Watch
The narrated version of this skribble — tap play for the full-size video.
0:00 / 1:27
Deep dive
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/finallyis the core mechanism
How It Works
When thrown, the JVM unwinds the stack looking for a match.
tryblocks contain risky codecatchhandles specific exception typesfinallynormally runs after try/catch (cleanup resources)- Checked:
IOExceptionmust be caught or declaredthrows - Unchecked:
NullPointerExceptionextendsRuntimeException
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
ClassCastExceptionrisk
Pitfalls and Best Practices
- Catch
specifictypes; broadExceptiononly at boundaries, neverThrowable - 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



