How to log uncaught exceptions in Java

Better Stack Team
Updated on August 25, 2023

In Java, uncaught exceptions can be logged using a combination of the Thread.UncaughtExceptionHandler interface and the setDefaultUncaughtExceptionHandler method. This allows you to define a global handler for uncaught exceptions that occur in your Java application. Here's a step-by-step guide on how to set up logging for uncaught exceptions:

Create a custom UncaughtExceptionHandler class that implements the Thread.UncaughtExceptionHandler interface. This class will define how uncaught exceptions are handled, such as logging the exception details.

import java.util.logging.Level;
import java.util.logging.Logger;

public class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final Logger LOGGER = Logger.getLogger(CustomUncaughtExceptionHandler.class.getName());

    public void uncaughtException(Thread t, Throwable e) {
        LOGGER.log(Level.SEVERE, "Uncaught exception in thread: " + t.getName(), e);

Set the custom UncaughtExceptionHandler as the default handler for uncaught exceptions using the setDefaultUncaughtExceptionHandler method. You can do this in the main method of your Java application or at an appropriate location where you want to set the global handler.

public class Main {
    public static void main(String[] args) {
        // Set custom uncaught exception handler
        Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());

        // Rest of your application code...

Now, if an uncaught exception occurs in any thread of your Java application, the CustomUncaughtExceptionHandler class's uncaughtException method will be called, and it will log the exception details using a logger (in this case, the Java Logger class).

Make sure to configure the logger to write the logs to a file or another appropriate destination based on your logging requirements. You can configure the logger's level, format, and other settings to suit your needs.

Note: This approach will handle uncaught exceptions in non-daemon threads. If you have daemon threads in your application that might throw uncaught exceptions, you should handle them explicitly within those threads or use a separate mechanism to catch and handle them.

To learn more about logging, visit Better Stack Community.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →