Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a Java thread terminated with exception?

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 ?

like image 803
Nicola Ferraro Avatar asked Dec 24 '14 16:12

Nicola Ferraro


People also ask

What is the use of exception with thread in Java?

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:

What happens if an Unchecked exception is thrown in 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.

How to suspend/stop a thread in Java?

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.");

How do you catch an exception in Java?

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.


1 Answers

Have you looked at Thread.setUncaughtExceptionHandler?

This lets you trap uncaufht exceptions if you have a handle on the thread?

like image 186
wmorrison365 Avatar answered Oct 18 '22 16:10

wmorrison365