How should you handle InterruptedException
s?
1 2 3 4 5 |
|
You could rethrow if it’s appropriate but often its not. If that’s the case, you should set the interrupt status flag associated with the current thread. For example,
1 2 3 4 5 |
|
Typically, if a Java method throws InterruptedException
, it will have reset the interrupt status before doing so. In the example above, you’re just restoring it and preserving a flag to indicate the thread had once been interrupted.
The reason for preserving this status flag is in case code other than your own depends on it. For example, a framework (which you may not appreciate is actually being used), may be doing something like the following to (correctly) support interruption.
1 2 3 |
|
You should generally never just catch the exception and ignore it; it may cripple code depending on the status flag for correct behaviour. In the same way, it’s rarely a good idea to catch and exception and just log it, especially in the case of InterruptedException
.