views:

313

answers:

4

in Java, if i start a thread T, from a main method in class A, and an exception occurs in T, how will the main method in A know about this. If im not wrong, an instance of Class A and the thread T will be present in two separate stacks, right, so, how does the parent of the thread get to know about the exception ?

+1  A: 

The question here may be of interest, though it may not be a direct answer.

Grundlefleck
+2  A: 

Short answer, it doesn't. If the exception propagates all the way out of the thread, it'll simply die (possible generating some error print on the console).

What you might be interested in doing though is to catch all exceptions in your outermost stack frame (i.e. your run-method, which started the thread), which puts the exception on a queue or other communication mechanism (perhaps along with some meta data such as thread id, etc) before the thread is terminated. The queue is then queried regularly by the parent thread (or use some other notification mechanism to wake up the parent thread, such as wait/notify or Condition-objects).

roe
hi, thnx.. this was helpful..
+2  A: 

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

I think it's a slightly better way than the try/catch block, since the mechanism of notifying the parent thread is decoupled from the thread code and can be reused for other threads.

patrigg
A: 

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

Hardcoded