Fundamentals 5 min read

Handling Uncaught Exceptions in Java Threads

This article explains how Java handles uncaught exceptions in threads, demonstrates setting per‑thread, thread‑group, and global exception handlers, and provides complete code examples illustrating each approach along with their execution results.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Handling Uncaught Exceptions in Java Threads

In Java, when a thread terminates due to an uncaught exception, the JVM looks up the thread's java.lang.Thread.UncaughtExceptionHandler via getUncaughtExceptionHandler and invokes its uncaughtException method; if none is set, the thread's ThreadGroup acts as the handler, eventually delegating to the default handler.

To set a handler for a specific thread, use Thread#setUncaughtExceptionHandler . The following example creates a thread with a custom handler that prints the exception message:

package com.renzhikeji.demo;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        ThreadGroup threadGroup = new ThreadGroup("认知科技技术团队-ThreadGroup") {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("threadGroup uncaughtException:" + e.getMessage());
            }
        };
        Thread thread = Thread.ofPlatform()
                .name("认知科技技术团队-thread")
                .uncaughtExceptionHandler((t, e) -> {
                    System.out.println("Thread UncaughtExceptionHandler:" + e.getMessage());
                })
                .start(() -> {
                    throw new RuntimeException("test exception");
                });
        thread.join();
        System.out.println(thread.isAlive());
    }
}

The program prints the custom handler message and shows that the thread has terminated.

When using a thread group, its uncaughtException method can be overridden to handle exceptions for all threads in the group, cascading up to parent groups and finally to the global default handler if none handle the exception.

package com.renzhikeji.demo;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        // Override thread group exception handling
        ThreadGroup threadGroup = new ThreadGroup("认知科技技术团队-ThreadGroup") {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("threadGroup uncaughtException:" + e.getMessage());
            }
        };
        Thread thread = Thread.ofPlatform()
                .group(threadGroup)
                .name("认知科技技术团队-thread")
                .start(() -> {
                    throw new RuntimeException("test exception");
                });
        thread.join();
        System.out.println(thread.isAlive());
    }
}

For a global handler that applies to all threads, call Thread#setDefaultUncaughtExceptionHandler before creating threads:

package com.renzhikeji.demo;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("Thread DefaultUncaughtExceptionHandler :" + e.getMessage());
            }
        });
        Thread thread = Thread.ofPlatform()
                .name("认知科技技术团队-thread")
                .start(() -> {
                    throw new RuntimeException("test exception");
                });
        thread.join();
        System.out.println(thread.isAlive());
    }
}

The output demonstrates that the default handler receives the exception message. The article concludes by noting that when using thread pools, developers may need to capture exceptions themselves rather than relying solely on these handlers to avoid unexpected thread termination.

concurrencyException HandlingThreaduncaught-exception
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.