What is the difference between the following ways of handling InterruptedException
? What is the best way to do it?
try{
//...
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
OR
try{
//...
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
EDIT: I'd like to also know in which scenarios are these two used.
Best Answer
You've probably come to ask this question because you've called a method that throws
InterruptedException
.First of all, you should see
throws InterruptedException
for what it is: A part of the method signature and a possible outcome of calling the method you're calling. So start by embracing the fact that anInterruptedException
is a perfectly valid result of the method call.Now, if the method you're calling throws such exception, what should your method do? You can figure out the answer by thinking about the following:
Does it make sense for the method you are implementing to throw an
InterruptedException
? Put differently, is anInterruptedException
a sensible outcome when calling your method?If yes, then
throws InterruptedException
should be part of your method signature, and you should let the exception propagate (i.e. don't catch it at all).If no, then you should not declare your method with
throws InterruptedException
and you should (must!) catch the exception. Now two things are important to keep in mind in this situation:Someone interrupted your thread. That someone is probably eager to cancel the operation, terminate the program gracefully, or whatever. You should be polite to that someone and return from your method without further ado.
Even though your method can manage to produce a sensible return value in case of an
InterruptedException
the fact that the thread has been interrupted may still be of importance. In particular, the code that calls your method may be interested in whether an interruption occurred during execution of your method. You should therefore log the fact an interruption took place by setting the interrupted flag:Thread.currentThread().interrupt()
By now it should be clear that just doing
throw new RuntimeException(e)
is a bad idea. It isn't very polite to the caller. You could invent a new runtime exception but the root cause (someone wants the thread to stop execution) might get lost.Other examples:
This post has been rewritten as an article here.