Back to results for “Global Exception Handling & Middleware”
Java › Exceptions

How would you design and implement a global, centralized exception-handling strategy for a Java application (such as a top-level handler in main(), or an uncaught exception handler for background threads), ensuring no exception silently crashes the application without being logged?

Advanced

Answer

Thread.setDefaultUncaughtExceptionHandler() (JVM-wide) or Thread.setUncaughtExceptionHandler() (per-thread) registers a callback invoked whenever an exception propagates uncaught out of a thread's run() method (which would otherwise silently terminate that thread with only a default stack-trace print to stderr, easy to miss in production, especially for a background worker thread whose termination might not be immediately obvious) -- a well-designed global handler ensures every uncaught exception is properly logged (with full context) through the application's actual logging infrastructure, potentially triggers alerting for critical failures, and for genuinely unrecoverable situations, can trigger a controlled, graceful application shutdown rather than leaving the application in a partially-broken state with a silently-dead thread.
public class Application {
    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> {
            logger.error("Uncaught exception in thread " + thread.getName(), exception);
            // optionally trigger alerting, or a controlled shutdown for critical failures
        });
        // ... application startup
    }
}
Real-world example A background worker thread pool's tasks were silently failing (an unhandled exception simply terminated the specific worker thread, with only a barely-noticed stderr print, while the rest of the application continued running seemingly normally) until a global UncaughtExceptionHandler was registered, properly logging and alerting on every such failure through the team's actual monitoring infrastructure instead of relying on someone happening to notice missing stderr output.

Common follow-ups: Why doesn't a try-catch in the main() method alone catch exceptions thrown on separate background threads?;How does this uncaught exception handler interact with exceptions occurring inside an ExecutorService-managed thread pool's tasks?