Home >Java >javaTutorial >How Can I Catch Exceptions Thrown by Threads in Java?
Catching Exceptions from Threads in Java
In multithreaded applications, managing exceptions thrown within different threads can be a challenge. Consider a scenario where a main class initiates a new thread and attempts to catch any runtime exceptions generated by it.
// Original Code public class CatchThreadException { public static void main(String[] args) throws InterruptedException { Thread t = new Thread() { @Override public void run() { throw new RuntimeException("Exception from thread"); } }; try { t.start(); t.join(); } catch (RuntimeException e) { System.out.println("** RuntimeException from main"); } System.out.println("Main stopped"); } }
In this code, the main thread waits for the child thread to complete using the join() method. However, when the child thread throws an exception, the main thread does not catch it.
Uncaught Exception Handler for Threads
To address this issue, Java provides a Thread.UncaughtExceptionHandler interface. By implementing this interface and assigning it to a thread, you can handle uncaught exceptions thrown within that thread.
// Using Uncaught Exception Handler public class CatchThreadException { public static void main(String[] args) throws InterruptedException { 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() { throw new RuntimeException("Exception from thread"); } }; t.setUncaughtExceptionHandler(h); t.start(); t.join(); System.out.println("Main stopped"); } }
In this modified code:
The above is the detailed content of How Can I Catch Exceptions Thrown by Threads in Java?. For more information, please follow other related articles on the PHP Chinese website!