try, catch, finally, and Exception Propagation
Exceptions propagate up the call stack until a matching handler is found. finally is intended for cleanup, although try-with-resources is usually safer for resources.
try {
process();
} catch (IllegalArgumentException e) {
System.err.println("Invalid input: " + e.getMessage());
} finally {
auditCompletion();
}
Catch specific exceptions rather than catching Exception everywhere. If an exception cannot be handled meaningfully at the current layer, propagate it with useful context.
Avoid empty catches
An empty catch block silently discards failures and makes production diagnosis extremely difficult.
Key Takeaways
- Catch exceptions where you can make a meaningful decision.
- Preserve context and causes when rethrowing.
- Do not use exceptions as normal high-frequency control flow.