Hi I have a problem with thread. I have written a thread class implementing runnable interface. In run method I am getting exception which need to be propagated back to the method that started the thread. I am not able to do this as I cant declare throws to run() method. Also throwing RuntimeException is not getting the exception to propogate back to the calling method.
I am not able to do this as I cant declare throws to run() method. Also throwing RuntimeException is not getting the exception to propogate back to the calling method.
Think about it. This code is running in another thread. The main thread is off doing something else -- probably not even directly related anymore. Or to put it another way, the "calling method" may have finished and returned, a long time ago.
Anyway, how did you implement getting the results sent back to the original thread? I am assuming that you stored it in a common location (which you synchronized. etc.). You just need to enhance that technique a bit.
Instead of storing just the result, you now need to store some flag whether an exception occurred, and of course, the exception too. In you run() method, you need to catch the exception so that you may store it.
As mentioned by Henry Wong, the caller method will start the thread and will continue (and may finish off) without waiting for result (or exception).
Hence, if your requirement is to catch the exception thrown in the thread in your caller method, the first thing you should be prepared for is having a synchronous (blocking) call from the caller method to the thread.
But then, multi-threading won't make much of a sense, would it? Your parent thread will simply 'hang' till the time child thread finishes off (or throws an exception). Although such a case sometimes becomes relevant (particularly in a Swing application).
Does your application have a GUI? If you could tell more about your requirements, may be folks can help you more.
Think of the thread that is run as a job. The thread that started it must periodically check to see the status of the job.
The job thread should wrap its run method in a try-catch block that catches Throwable and stores it before shutting itself down. The main thread can then request this exception from the job thread when it gets around to it.