Java error handling guide: checked vs unchecked exceptions, try-with-resources, custom exceptions, Result/Either pattern, and logging exceptions.
Error Handling: Exceptions, Try-with-Resources, and Result Patterns
Good error handling is the difference between an application that crashes mysteriously and one that fails gracefully with actionable information. This page covers Java's exception model, resource management, and functional alternatives.
Exception hierarchy
Checked vs unchecked exceptions
Checked exceptions
The compiler forces you to handle them (try/catch or declare throws):
Unchecked exceptions
No compiler enforcement - they indicate programming errors or precondition violations:
When to use which
Modern Java style leans toward unchecked exceptions for most application-level errors, reserving checked exceptions for truly recoverable I/O operations.
Try-with-resources
Automatically closes AutoCloseable resources when the block exits (normally or via
exception):
Implementing AutoCloseable
Suppressed exceptions
If both the try block and the close() method throw, the close exception is
suppressed (attached to the primary exception):
Custom exception hierarchies
Base exception
Specific exceptions
Usage
Multi-catch and finally
Prefer try-with-resources over
finallyfor resource cleanup. Usefinallyonly for non-resource cleanup logic.
Result / Either pattern
A functional alternative to exceptions for expected failure cases. The method returns a value that explicitly represents success or failure:
Simple Result type
Usage
When to use Result vs Exceptions
Logging exceptions properly
Exception handling in streams
Streams do not support checked exceptions. Workarounds: