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.
Class InterruptedException. Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.
(b) RuntimeException signals a programming error; InterruptedException is not a result of a programming an error. InterruptedExceptions are particular complicated to handle, when they happen you need to care about the interrupt flag of the thread, and it can only happen in blocking operations.
InterruptedExceptions should never be ignored in the code, and simply logging the exception counts in this case as "ignoring".
What is the difference between the following ways of handling InterruptedException? What is the best way to do it?
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 an InterruptedException
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 an InterruptedException
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).
Example: Your method waits for a value from the network to finish the computation and return a result. If the blocking network call throws an
InterruptedException
your method can not finish computation in a normal way. You let theInterruptedException
propagate.int computeSum(Server server) throws InterruptedException { // Any InterruptedException thrown below is propagated int a = server.getValueA(); int b = server.getValueB(); return a + b; }
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()
Example: The user has asked to print a sum of two values. Printing "
Failed to compute sum
" is acceptable if the sum can't be computed (and much better than letting the program crash with a stack trace due to anInterruptedException
). In other words, it does not make sense to declare this method withthrows InterruptedException
.void printSum(Server server) { try { int sum = computeSum(server); System.out.println("Sum: " + sum); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // set interrupt flag System.out.println("Failed to compute sum"); } }
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:
Implementing
Runnable
: As you may have discovered, the signature ofRunnable.run
does not allow for rethrowingInterruptedExceptions
. Well, you signed up on implementingRunnable
, which means that you signed up to deal with possibleInterruptedExceptions
. Either choose a different interface, such asCallable
, or follow the second approach above.
Calling
Thread.sleep
: You're attempting to read a file and the spec says you should try 10 times with 1 second in between. You callThread.sleep(1000)
. So, you need to deal withInterruptedException
. For a method such astryToReadFile
it makes perfect sense to say, "If I'm interrupted, I can't complete my action of trying to read the file". In other words, it makes perfect sense for the method to throwInterruptedExceptions
.String tryToReadFile(File f) throws InterruptedException { for (int i = 0; i < 10; i++) { if (f.exists()) return readFile(f); Thread.sleep(1000); } return null; }
This post has been rewritten as an article here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With