views:

68

answers:

2

In Java, Thread.sleep() throws InterruptedException. What is the proper thing to do with this exception?

  1. propagate the exception as a failure up the call chain
  2. eat the exception and proceed with your code
  3. other
+7  A: 

You should rethrow the exception.

This is an abstract from Brian Goetz, the author of the excellent book "Java Concurrency in Practice":

Dealing with InterruptedException:

If throwing InterruptedException means that a method is a blocking method, then calling a blocking method means that your method is a blocking method too, and you should have a strategy for dealing with InterruptedException. Often the easiest strategy is to throw InterruptedException yourself, as shown in the putTask() and getTask() methods in Listing 1. Doing so makes your method responsive to interruption as well and often requires nothing more than adding InterruptedException to your throws clause.

See : Dealing with InterruptedException

Thierry-Dimitri Roy
Another possibility is to re-assert the interrupt status immediately. Thread.currentThread().interrupt(). This is sometimes useful if you don't control the API that is being called (perhaps you are implementing some 3rd party interface), but you want the interrupt status to be preserved so it can be "noticed" be a later check/blocking method.
Mike Q
A: 

If all you're trying to do is burn SOME time, I would suggest just catching and ignoring the exception.

If, on the other hand, you need the proper amount of waiting time and any preemptive interruption is REALLY BAD for your program, then you should definitely rethrow the exception.

It just depends on why the exception occurred and what your use case is for Thread.sleep() in the first place.

Platinum Azure