Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Exception in a child thread

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 ?

like image 986
user221327 Avatar asked Nov 30 '09 13:11

user221327


People also ask

What happens if an exception is thrown in a thread?

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.

Can you catch an exception thrown by another thread in Java?

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.


1 Answers

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

like image 114
falstro Avatar answered Sep 22 '22 00:09

falstro