重新中断此方法或抛出“在声纳中发生的InterruptedException问题”。

48

在我的一个方法中,出现了中断异常和执行异常。我像这样放在try catch块中。

try{

  //my code
}catch(InterruptedException|ExecutionException e)

  Log.error(" logging it");
  throw new MonitoringException("it failed" , e)


//monitoringexception extends RunTimeException

我的方法中也放置了 throws InterruptedException,ExecutionException

我在 Sonar 中遇到以下严重错误 - 要么重新中断该方法,要么重新抛出 "InterruptedException"

有人知道如何解决吗?

请立即提供帮助。


3
请参见https://dev59.com/jW865IYBdhLWcg3wHK3u,其中讨论了如何在Java中处理InterruptedException。 - user7294900
1个回答

76

为了作为最佳实践"重新中断(re-interrupt)":

try{
    //some code
} catch (InterruptedException ie) {
    logger.error("InterruptedException: ", ie);
    Thread.currentThread().interrupt();
} catch (ExecutionException ee) {
    logger.error("ExecutionException: ",ee);
}

通常情况下,当一个线程被中断时,触发中断的人希望该线程退出当前操作。

然而,请确保不要使用多重捕获(multi-catch):

catch (InterruptedException | ExecutionException e) {     
  logger.error("An error has occurred: ", e);
  Thread.currentThread().interrupt();
}

我们不希望ExecutionException被"重新中断"。

BONUS:
如果您感兴趣,可以尝试操作此处的示例


干杯


3
我的 VS Code 显示第二个 catch 是无法到达的代码。 - Jawad El Fou

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接