In a Java multi-threaded program, all threads are not allowed to throw uncaught checked exceptions, which means that each thread needs to handle its own checked exceptions. This is constrained by the java.lang.Runnable.run() method declaration (because there is no throw exception part on this method declaration). However, the thread may still throw an unchecked exception. When such an exception is thrown, the thread will terminate, and the main thread and other threads will not be affected at all, and the exception thrown by a certain thread will not be perceived at all (also It says that this exception cannot be caught at all). This design of the JVM originates from the concept: "Threads are independently executed code fragments. Thread problems should be solved by the thread itself rather than delegated to the outside." Based on this design concept, in Java, threads Method exceptions (whether checked or unchecked exceptions) should be try caught and handled within the thread code boundaries (within the run method).
But if the thread does not try to catch an unchecked exception by itself, and we want to catch and handle this exception outside the thread code boundaries (outside the run method), Java provides us with a way to catch an exception when an exception occurs within the thread. The callback mechanism for handling exceptions outside the thread code boundary is the setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) method provided by the Thread object.
By setting an UncaughtExceptionHandler for a thread through this method, you can ensure that when an exception occurs in the thread, the exception can be handled by calling back the public void uncaughtException(Thread t, Throwable e) method of the UncaughtExceptionHandler interface. The advantage or purpose of this is that it can be used in the thread Outside the code boundaries (outside Thread's run() method), there is a place to handle uncaught exceptions. But what should be particularly clear is that although the exception is handled in the callback method, the callback method is still in the thread that threw the exception when it is executed!
Compared with the above method, there is another programming method that can be used for reference. That is, sometimes the caller of the main thread may just want to know what exceptions have occurred during the execution of the sub-thread, but may not necessarily handle them or handle them immediately. Then The method of initiating a child thread can collect the exception instances thrown by the child thread and return it to the caller as a List of Exceptions, and the caller can decide how to respond according to the abnormal situation. However, it is important to note that the child thread has already terminated at this time.