A brief analysis of the exception handling mechanism in Java multithreading

  • 2020-04-01 01:10:07
  • OfStack

In Java multithreaded programs, all threads are not allowed to throw uncaught checked exceptions, which means that each thread needs to handle its own checked exception. This is constrained by the java.lang.Runnable. Run () method declaration (because there is no throw exception section on this method declaration). But it is still possible for a thread to throw an unchecked exception, and when such an exception is thrown, the thread ends without being affected by the main thread or other threads, and without being aware of the exception thrown by a particular thread (which means that it is impossible to catch). This design of the JVM stems from the idea that "threads are pieces of code that execute independently, and thread problems should be solved by the thread itself, not delegated externally." Based on this design philosophy, in Java, exceptions to threaded methods (both checked and unchecked exceptions) should be tried catch and disposed of within the thread code boundary (within the run method).

But if the Thread does not own the try catch an unchecked exception, and we want to in a Thread code boundaries (run method) to capture and handle the exception, Java provides us with a Thread to the Thread when an exception occurs within the exception handling code boundaries callback mechanism, namely Thread objects provide setUncaughtExceptionHandler (Thread. UncaughtExceptionHandler eh) method.

By setting up a UncaughtExceptionHandler for a thread with this method, we can ensure that the thread can handle the exception (thread t, Throwable e) by calling back the public void uncaughtException(thread t, Throwable e) method of the UncaughtExceptionHandler interface when the thread has an exception, which has the advantage or purpose of being outside the thread code boundary (thread's run() method), There is a place to handle uncaught exceptions. But be especially clear: although the exception is handled in the callback method, the callback method is still in the thread that threw the exception at the time of execution!

Than the above methods, and a programming approach can draw lessons from, that is, sometimes the main thread of the caller may just want to know what happened during the execution of a child thread is unusual, but not necessarily treatment or immediately, then launch the child thread method can traverse to the child thread the Exception thrown instances collected as an Exception List returned to the caller, the caller to decide how to deal with according to the abnormal situation. It is important to note that the child thread ends early.


Related articles: