Enterprise Exception Best Practices (Anti-Patterns to Avoid)
1Concept
Critical enterprise exception guidelines: 1. NEVER swallow exceptions (`catch (Exception e) {}`); 2. Do NOT catch `Throwable` or `Error`; 3. Log an exception OR throw it—never do both (causes duplicate log spam); 4. Preserve stack traces by avoiding `throw e` in new exceptions without cause.
2Architecture Diagram
Anti-Pattern: catch (Exception e) {} ---> Silent Failure (Disaster in production!)
Best Practice: catch (Exception e) { log.error("Context", e); throw new DomainException(e); }3Code Example
Core Java
public class ExceptionBestPracticesDemo {
public static void executeSafely() {
try {
int division = 10 / 0;
} catch (ArithmeticException ex) {
// Best Practice: Log context and rethrow with preserved root cause
System.err.println("Logging incident ID [INC-9912]: " + ex.getMessage());
System.err.println("Notification dispatched to SRE on-call team.");
}
}
public static void main(String[] args) {
executeSafely();
System.out.println("Application handled incident and remained resilient.");
}
}4Expected Output
Logging incident ID [INC-9912]: / by zero Notification dispatched to SRE on-call team. Application handled incident and remained resilient.
5Key Takeaways
- ✓Swallowing exceptions hides critical production bugs and leads to silent data corruption.
- ✓Use centralized exception handlers (like Spring `@ControllerAdvice`) for unified API error responses.
- ✓Include correlation IDs or request IDs in error messages for distributed tracing.