Home >Java >javaTutorial >How Can I Handle Exceptions Thrown from Child Threads in Java?

How Can I Handle Exceptions Thrown from Child Threads in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 16:37:19824browse

How Can I Handle Exceptions Thrown from Child Threads in Java?

Handling Exceptions Thrown from Threads

In multi-threaded applications, it's essential to handle exceptions thrown by child threads in the main thread. Consider the following scenario:

<br>public class Test extends Thread {<br>  public static void main(String[] args) throws InterruptedException {</p>
<pre class="brush:php;toolbar:false">Test t = new Test();

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

System.out.println("Main stoped");

}

@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 example, an exception thrown in the child thread doesn't propagate to the main thread. This is because Java doesn't automatically associate exceptions thrown in threads with handlers in the main thread.

Solution: Thread.UncaughtExceptionHandler

To handle exceptions from threads, one can use a Thread.UncaughtExceptionHandler. This interface provides a method uncaughtException() that gets called when an uncaught exception occurs in a thread.

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();

By setting the uncaughtExceptionHandler to the thread, any uncaught exceptions will be handled by the provided implementation. This allows the main thread to capture and process exceptions gracefully, ensuring proper handling and error reporting.

The above is the detailed content of How Can I Handle Exceptions Thrown from Child 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