Given a thread that has finished doing some work (its status is Thread.State.TERMINATED), is there a way to understand if the thread has completed the Thread.run()/Runnable.run() method correctly or has thrown an uncaught throwable ?
Afaik, a thread goes into the TERMINATED state both when exiting normally and when throwing throwables.
Somebody suggested using an UncaughtExceptionHandler. Given that a thread can have only one UncaughtExceptionHandler (other than the default for all threads), and that the thread code can change the provided one, is it a good practice using them ?
Uncaught exception handler will be used to demonstrate the use of exception with thread. It is a specific interface provided by Java to handle exception in the thread run method. There are two methods to create a thread:
Unchecked exceptions don’t have to be specified or caught. When a checked exception is thrown inside the run () method of a Thread object, we have to catch and handle it accordingly, because the run () method doesn’t accept a throws clause.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread.interrupt () method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say ‘exit’. Whenever we want to stop a thread, the ‘exit’ variable will be set to true. System.out.println (name + " Stopped.");
When a method encounters an abnormal condition that it can not handle, an exception is thrown as an exception statement. Exceptions are caught by handlers (here catch block). Exceptions are caught by handlers positioned along with the thread’s method invocation stack.
Have you looked at Thread.setUncaughtExceptionHandler?
This lets you trap uncaufht exceptions if you have a handle on the thread?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With