简体   繁体   English

在生产者/消费者等多线程程序中,Swallowing InterruptedException的目的是什么

[英]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. 这通常表示开发人员不知道如何处理Exception,因此只是忽略了它。

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. 调用Thread.currentThread()。interrupt(),以使中断不会丢失。
  • If such an exception should be impossible, wrap it in a throw new AssertionError(ex) 如果这样的异常不可能发生,则将其包装为一个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. 这用于可能发生异常但对异常的响应与try块的正常继续相同的情况。 A common example is calling sleep(). 一个常见的示例是调用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. InterruptedException是所谓的检查异常。 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. 暂时假设您在try块中有6-7条语句,并假设它们将以或多或少的原子方式运行。 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; 给定任何显示这种行为的示例代码,我猜想其中没有捕获逻辑,因为a)程序员没有应对它的计划; b) the programmer merely wanted to step past the check so the code compiles. b)程序员只想跳过检查,以便代码编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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