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 ?
An exception thrown in a spawned worker thread will cause this thread to be silently terminated if the exception is unhandled. You need to make sure all exceptions are handled in all threads. If an exception happens in this new thread, you want to handle it and be notified of its occurrence.
There does not exist a way in Java to use try/catch around your start() method to catch the exceptions thrown from a secondary thread and remain multithreaded.
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).
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