Home >Java >javaTutorial >How to Handle Uncaught Exceptions Thrown by Threads in Java?

How to Handle Uncaught Exceptions Thrown by Threads in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 09:52:101066browse

How to Handle Uncaught Exceptions Thrown by Threads in Java?

Catching Exceptions Thrown by Threads

In Java, when a new thread is created, it executes its run() method concurrently with the main thread. However, exceptions thrown within a thread cannot be directly handled in the main class.

Consider the following code:

public class Test extends Thread {
  public static void main(String[] args) throws InterruptedException {
    Test t = new Test();

    try {
      t.start();
      t.join();
    } catch(RuntimeException e) {
      System.out.println("** RuntimeException from main");
    }

    System.out.println("Main stopped");
  }

  @Override
  public void run() {
    try {
      while(true) {
        System.out.println("** Started");

        sleep(2000);

        throw new RuntimeException("exception from thread");
      }
    } catch (RuntimeException e) {
      System.out.println("** RuntimeException from thread");

      throw e;
    } catch (InterruptedException e) {

    }
  }
}

In this code, a runtime exception is thrown from the thread, but it is not caught in the main class. To address this issue, Java provides a convenient mechanism called a Thread.UncaughtExceptionHandler.

Using Thread.UncaughtExceptionHandler

A Thread.UncaughtExceptionHandler provides a way to handle exceptions that are not caught within a thread. To use it, assign a handler to the thread using setUncaughtExceptionHandler() and override its uncaughtException() method to define the exception-handling logic.

Here's an example:

Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};
Thread t = new Thread() {
    @Override
    public void run() {
        System.out.println("Sleeping ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
        }
        System.out.println("Throwing exception ...");
        throw new RuntimeException();
    }
};
t.setUncaughtExceptionHandler(h);
t.start();

In this code, the handler prints the uncaught exception to the console. By using the Thread.UncaughtExceptionHandler, exceptions thrown within a thread can be handled effectively in the main class.

The above is the detailed content of How to Handle Uncaught Exceptions Thrown by Threads in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn