简体   繁体   中英

In the multi-thread program like producer/consumer, what's the purpose of Swallowing InterruptedException

有些代码只调用catch(ex。InterruptedException){},为什么呢?

This is usually a sign that the developer didn't know how to handle the Exception and thus just ignored it.

This is the sort of bad behaviour that results in some saying checked exceptions are a failed experiment. IMHO Developers should just learn to handle exceptions.

A better way to handle this exception is to either

  • pass it to the caller. ie don't catch it.
  • call Thread.currentThread().interrupt() so the interrupt is not lost.
  • If such an exception should be impossible, wrap it in a throw new AssertionError(ex)

That is used in situations where an exception may occur but the response to the exception is the same as normal continuation from the try block. A common example is calling sleep(). (However, that's actually often a bad example because being interrupted often signals that an operation should be abandoned.)

InterruptedException is what's called a checked exception. When added to a method you want to call, it's a way of signifying that you must account for this situation, namely that the time you need to process the results of the call may be pre-empted by another thread in the system.

Assume for the moment that you have 6-7 statements in a try block, and you assume they will run in a more or less atomic fashion. Among those statements is one that relies on thread-aware behavior. If that call is pre-empted, your subsequent statements won't run, and you'll have to handle the consequences.

People have all sorts of reasons for catching this exception but taking no action. I can't think of many good reasons for doing this, unless I can clearly show that being interrupted doesn't create an undesirable side-effect in my code. Given any example piece of code that shows this behavior, I would guess no catch logic was included because a) the programmer had no plan for dealing with it; b) the programmer merely wanted to step past the check so the code compiles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM