Java: exception in child thread

in Java, if I start a thread T, from the main method in class A, and an exception occurs in T, as the main method in A will know about it. If im not so, an instance of class A and thread T will be present in two separate stacks, right, so how can the thread parent know about the exception?

+4
source share
3 answers

The short answer is, it is not. If the exception extends to the entire exit from the stream, it will simply die (it may generate some error on the console).

What you might be interested in is to catch all the exceptions in your external stack frame (i.e. your run-method that started the thread) that puts the exception in a queue or other communication mechanism (perhaps along with some metadata, such as stream identifier, etc.) until the stream stops. Then the queue is requested regularly by the parent thread (or uses some other notification mechanism to wake up the parent thread, such as wait / notify or Condition-objects).

+6
source

Instead of surrounding the stream code with a try / catch block and informing the parent stream, as explained in previous comments, you can override UncaughtExceptionHandler . The mechanism is described in detail here . You can also look in the Java documentation for Interface Thread.UncaughtExceptionHandler .

I think this is slightly better than the try / catch block, as the parent thread notification mechanism is untied from the thread code and can be reused for other threads.

+4
source

If no one explicitly notifies the stream, it will not notice. Perhaps UncaughtExceptionHandler can help you catch uncaught exceptions. Additional you need a way to notify the main thread.
This can be done by calling interrupt () or using pipes, notify () / condition.await (), etc.

0
source

All Articles