I have one main thread it has created many workers, every worker is a thread.
How can I get errors from the workers in main thread if there was an Exception in some worker or worker cannot successfully ended ?
How to send error before the worker thread dead ?
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: Extend the thread Class (java.
We simply placed a try/catch block around the start() method. After all, start() instantiates the secondary thread and calls its run() method and the use of try/catch is the natural way of dealing with exceptions. If the code in run() throws any exceptions we should be able to catch them.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
Exception handling in Thread : By default run() method doesn't throw any exception, so all checked exceptions inside the run method has to be caught and handled there only and for runtime exceptions we can use UncaughtExceptionHandler.
If you use the java.util.concurrent Executor frameworks and generate a Future from each submitted worker, then calling get() on the Future will either give you the worker's result, or the exception thrown/caught within that worker.
You can set global UncaughtExceptionHandler which will intercept all uncaught Exceptions in all threads
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
...
}
});
Use ExecutorService or ThreadPoolExecutor
You can catch Exceptions in three ways
run() or call()
method in try{}catch{}Exceptoion{}
blocksafterExecute
method of ThreadPoolExecutor Refer to below SE question for more details:
Handling Exceptions for ThreadPoolExecutor
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