If an Exception occurs at some point in Java code, the control goes to the catch block. However, If this code is actually inside a multi-threaded run() method, how do I instruct the code the to finish with the run() method when the Exception occurs?
In other words, how can I instruct the thread that the run() method has finished, because it knows that an Exception has occurred?
If you’re in the
run()method of yourThread, you can simplyreturn, which terminates theThreadin the same way that callingreturnin any other method ends the method processing.Maybe something like this, where you watch for an
Exceptionand callreturnif theExceptionoccurs…However, if your
Threadhas multiple methods, the best way might be to have each method declare that it can throw anException. For example, if yourThreadis like this…See how each of the other methods can throw an
Exception. So, if anExceptionis thrown in any of the methods of thisThread, it will trigger thetry-catchof therun()method, andreturnout of theThread, thus terminating it.Of course, if the
try-catchin yourrun()method covers all the code of the method, you don’t need to actuallyreturn, because it is implicit when it reaches the end of therun()method anyway.