尝试/捕获每一个抛出异常的单个语句都被视为反模式? [英] Are try/catch for every single statement that throws an exception considered an anti-pattern?

查看:190
本文介绍了尝试/捕获每一个抛出异常的单个语句都被视为反模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审查同事的Java代码,我看到很多情况下,每一个可能引发异常的声明都封装在自己的try / catch中。 catch块全部执行相同的操作(该操作与我的问题无关)。



对我来说,这似乎是一个代码气味,我记得读它是一种常见的反模式。然而,我找不到任何参考。



所以尝试/捕获每一个抛出和异常的声明都是反模式,支持这个的论据?






构造示例:
(与原始问题无关,所以请不要介意这个例子的其他问题,因为它只是构造来说明我的意思。)

  public int foo()
{
int x,y = 7;

try
{
x = bar(y);
}
catch(SomeException e)
{
return 0;
}

try
{
y = baz(x,y);
}
catch(SomeOtherException e)
{
return 0;
}

/ *等* /

return y;
}

(假设在这里捕获这两个异常都是适当的,即我们知道在这两种情况下,适当的事情是返回0)

解决方案

我无法为您服务权威来源,但这些是异常处理的基本原则:




  • 异常应该被捕获到可以正确处理它们的位置, / li>
  • 你不能吞下异常 - 总是有(至少)一个异常抛出的痕迹,所以最小的是记录它,所以至少开发人员有机会注意发生了什么坏事这导致第三点:

  • 异常只能用于指示特殊的不良事件,而不是控制程序流。



有很多关于SO处理这个问题的帖子,例如 JAVA或C#中的异常管理最佳做法


I am currently reviewing a colleagues Java code, and I see a lot of cases where every single statement that may throw an exception being encapsulated in its own try/catch. Where the catch block all perform the same operation (which operation is not relevant for my question).

To me this seems like a code smell, and I do remember reading about it being a common anti-pattern. However I cannot find any references on this.

So are try/catch for every single statement that throws and exception considered an anti-pattern, and what are the argument supporting this?


Constructed example: (Does not relate to the original problem, so please don't mind other problems with this example, as it is just constructed to illustrate what I mean.)

public int foo()
{
    int x, y = 7;

    try
    {
        x = bar(y);
    }
    catch(SomeException e)
    {
        return 0;
    }

    try
    {
        y = baz(x,y);
    }
    catch(SomeOtherException e)
    {
        return 0;
    }

    /* etc. */

    return y;
}

(Assume that it is appropriate to catch both exceptions here, i.e. we know what do with them, and the appropriate thing is to return 0 in both cases.)

解决方案

I can't serve you with an authoritative source, but these are fundamental tenets of exception handling:

  • exceptions should be caught at the point where one can properly handle them, and
  • you must not swallow exceptions - there should always be (at least) a trace of an exception thrown, so the minimum is to log it, so that at least the developers get a chance of noticing that something bad happened. Which leads to the third point:
  • exceptions should only be used to signal exceptional bad events, not to control program flow.

There are lots of earlier posts on SO dealing with this, for example Best practices for exception management in JAVA or C#.

这篇关于尝试/捕获每一个抛出异常的单个语句都被视为反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆