If you are using regular Try...catch to handle exceptions thrown from threads
Package Exception;
public class Exceptionthread extends Thread
{public
void run ()
{
throw new runtimeexception ();
} Public
static void Main (string[] args)
{
Exceptionthread thread = new Exceptionthread ();
Try
{
thread.start ();
}
catch (RuntimeException e)
{
System.out.println ("Handler the exception");
}
}
Running the above code will get java.lang.RuntimeException hints, so you can see the use of Try ... Catch cannot catch an exception thrown from a thread.
How do I handle exceptions thrown from threads? Here you need to understand a nested class Thread.uncaughtexceptionhandler in the thread class, which you can see by name as a class that does not handle exceptions in the thread class.
Interpreted in the API public
static interface Thread.uncaughtexceptionhandler The interface that invokes the handler when Thread terminates abruptly because of an unhandled exception.
when a thread is about to terminate due to an exception that is not caught, the Java virtual machine uses Thread.getuncaughtexceptionhandler () to query it to obtain its Uncaughtexceptionhandler thread. and calls the handler's Uncaughtexception method, passing the thread and exception as parameters. If a thread does not explicitly set its Uncaughtexceptionhandler, its Threadgroup object is used as its uncaughtexceptionhandler. If the Threadgroup object has no special requirements for handling exceptions, it can forward the call to the default unhandled exception handler.
public class Catchthreadexception
{public
static void Main (string[] args)
{
Executorservice exec = Executors.newcachedthreadpool (New Handlerthreadfacotry ());
Exec.execute (New ThreadException ());
}
Class ThreadException implements Runnable
{public
void run ()
{
throw new runtimeexception ();
}
}
Class Mythreadexceptionhandler implements Uncaughtexceptionhandler
{public
void Uncaughtexception (Thread T, Throwable e)
{
System.out.println ("Exception handler");
}
Class Handlerthreadfacotry implements Threadfactory
{public
Thread Newthread (Runnable r)
{
thread thread = new Thread (r);
Thread.setuncaughtexceptionhandler (New Mythreadexceptionhandler ());
return thread;
}
The result of running the above code is that exception handler ThreadException is a class that implements the Runnable interface, throws an exception in its Run method,
Executors.newcachedthreadpool (New Handlerthreadfacotry ())
We implement a thread pool and specify the factory method that produces the threads, in which we call Thread.setuncaughtexceptionhandler () for each thread in the factory method to specify an exception handling handler, when the thread throws an exception. The Uncaughtexception () method of the specified handler is executed, and the parameters are automatically passed in by the JDK.