| Author |
How can a checked exception be thrown from run method of a thread ?
|
Kumar Raja
Ranch Hand
Joined: Mar 18, 2010
Posts: 457
|
|
Hi All,
Probably I know that many of you might be asking me "Why" do I want to throw a checked exception from a run() method of a Thread (either by inheriting Thread or implementing Runnable), but I'm just curious if at all there is some way of capturing the exception, so that some thing meaning ful can be done instead of looking at the program dying, miserably.
A little background on this problem. I'm trying to write a small program (JMS implementation) where I have two thread (Producer and Consumer) sending and consuming the messages. I want to throw the exception back to the calling module, which actually starts these thread to execute. How can this be achieved, if at all possible. If not, what work arounds do we have.
|
Regards
KumarRaja
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Thread and Runnable are not meant to handle exceptions. Java 5.0 introduced the java.util.concurrent package that includes interface Callable. It is basically the same as Runnable, but its only method (called call) returns a value and can throw any exception. You can use ExecutorService.submit to turn this Callable into a Future. With that Future you can call one of its "get" methods to wait for the Callable to finish and return its value.
A small example:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: How can a checked exception be thrown from run method of a thread ?
|
|
|