Java - Exceptions & Error Handling
Exceptions & Error Handling
Checked vs Unchecked
- Checked: must be declared or caught (e.g., IOException, SQLException).
- Unchecked: RuntimeException and subclasses (e.g., NullPointerException, IllegalArgumentException).
try/catch/finally
try {
risky();
} catch (SpecificException e) {
// recover or wrap with context
} catch (Exception e) {
// last-resort handler
} finally {
cleanup();
}
Try-with-Resources
import java.nio.file.*;
try (var reader = Files.newBufferedReader(Path.of("file.txt"))) {
System.out.println(reader.readLine());
} catch (java.io.IOException e) {
e.printStackTrace();
}
Custom Exceptions
class DomainException extends RuntimeException {
DomainException(String msg) { super(msg); }
}
Best Practices
- Throw exceptions to indicate exceptional states; don’t use for control flow.
- Prefer specific exception types; add context (IDs, parameters) to messages.
- Don’t swallow exceptions; either handle or rethrow with context.
- Log once, at the boundary; avoid duplicate logs for the same failure.
Architect note: Establish error-handling conventions (wrapping strategy, logging format, mapping to HTTP or user-visible errors) and enforce with tests.
Try it
- Wrap file reading in try-with-resources; print a helpful message if the file is missing.
- Create a custom runtime exception and throw it when an invariant is violated.