Is it OK to ignore InterruptedException if nobody calls interrupt()?

Hilikus picture Hilikus · Feb 16, 2015 · Viewed 13.3k times · Source

If I create my own thread (i.e. not a threadpool) and somewhere I call sleep or any other interruptible method, is it ok to ignore the InterruptedException if I know nobody else in the code is doing an interrupt on the thread.

In other words, if the thread is supposed to live as long as the JVM, meaning the thread is not interruptible, is it safe to assume that InterruptedException will never be called and therefore the exception can be swallowed?

Answer

Zhedar picture Zhedar · Feb 16, 2015

Ignoring a checked exception is never considered to be safe.
It may be ok for you at the moment, but if another programmer extends your code, he will expect the standard behaviour: the thread reacting to an interrupt call.
Also an empty catch block is dangerous in this case, since the JVM removes the interrupted flag and it should definitely be set again with

Thread.currentThread().interrupt();

in the catch block. In my opinion, this is the minimum catch implementation for InterruptedExceptions. Checking for the isInterrupted flag in a loop doesn't hurt much, either.
It is little overhead compared to your future programmer self's hassle searching a day or two for unexpected thread behaviour as you project may have grown a bit.

If you feel that your code's readability suffers from those catch implementations, you may implement your own safeSleep utility method, which takes care of the Exceptions and sets the flag properly.

On the other hand, InterruptedException is not thrown by the JVM itself in case of a hardware failure, it is a user indicated Exception only. So, if you do not propagate your Threads reference, there won't be any other Threads that are able to call Thread.interrupt() on it. That's it technically. But you shouldn't underestimate the human factor and your programs evolution.
Edit: As ruakh pointed out, there actually is a way to get a Threads reference and thus to schedule an Thread.interrupt() call. That way the developer in heat may not even have to look at the class, that implements your uninterruptible Thread. In my opinion that's even another reason, to implement proper exception handling.
Another thing: If you're not throwing an Exception, logging such an event on a level beyond INFO may be a good choice.