• Post Reply Bookmark Topic Watch Topic
  • New Topic

How can a checked exception be thrown from run method of a thread ?  RSS feed

 
Kumar Raja
Ranch Hand
Posts: 550
2
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!