Why would you catch InterruptedException to call Thread.currentThread.interrupt()? Why would you catch InterruptedException to call Thread.currentThread.interrupt()? multithreading multithreading

Why would you catch InterruptedException to call Thread.currentThread.interrupt()?


The simple answer is that InterruptedException is a checked exception and it is not in the signature of the Runnable.run method (or the Executable.execute() method). So you have to catch it. And once you've caught it, calling Thread.interrupt() to set the interrupted flag is the recommended thing to do ... unless you really intend to squash the interrupt.


Sometimes you can't ignore exception and you must catch it. Mainly this happens when you override method which can't throw InterruptedException in accordance with its signature. For example, this approach is usually used in Runnable.run() method.


The executor can interrupt tasks if they are cancelled but it clears the interrupted flag between tasks to avoid one cancelled task interrupting an unrelated task.

As such, interrupting the current thread here would be dangerous if it actually did anything.

A simpler way around this is to use Callable or ignore the interrupt.

Additionally it is a good idea to catch and log any error or exception thrown in the try/catch block otherwise the exception/error will be discarded and your program could be failing but you won't know it is or why.