这是一个不好的做法,赶上非特异性异常如System.Exception的?为什么?这是一个、异性、做法、异常

2023-09-02 10:29:07 作者:好听的今日头条昵称

我目前做了code审查和下面的code把我吓了一跳。我看到这个code多的问题。你是否同意我的观点?如果是这样,我怎么解释给我的同事,这是错误的(顽固型...)?

抓住一个通用的异常(异常前) 在使用如果(当然是后话),而不是有另一个catch块 我们吃的SoapException,HttpException和WebException。但是,如果Web服务失败,不是有很多工作要做。

code:

 尝试
{
    //调用到WebService
}
赶上(例外前)
{
    如果(前是的SoapException ||当然是HttpException ||当然是WebException)
    {
        //日志错误和熊掌兼得。
    }
    其他
    {
        扔;
    }
}
 

解决方案

的口头禅是:

您应该仅捕获异常 你可以妥善处理

这样:

您不应该赶上一般 异常。

在你的情况,是的,你应该只捕捉那些异常并做一些有益的(可能不只是吃它们 - 你能登录之后他们)。

吓坏了 体检查出CEA和CA199升高,这是得了胃癌吗 胃镜检查发现......

您codeR使用抛出(而不是抛出前),这是的好。

这是你如何能赶上多,特殊情况例外:

 尝试
{
    //调用到WebService
}
赶上(的SoapException前)
{
    //日志错误和熊掌兼得
}
赶上(HttpException前)
{
    //日志错误和熊掌兼得
}
赶上(WebException前)
{
    //日志错误和熊掌兼得
}
 

这是pretty的多少等同于你的code一样。你的开发可能没有这样的说法,以避免重复的日志中的错误和熊掌兼得的块。

I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? If so, how do I explain to my colleague that this is wrong (stubborn type...)?

Catch a generic exception (Exception ex) The use of "if (ex is something)" instead of having another catch block We eat SoapException, HttpException and WebException. But if the Web Service failed, there not much to do.

Code:

try
{
    // Call to a WebService
}
catch (Exception ex)
{
    if (ex is SoapException || ex is HttpException || ex is WebException)
    {
        // Log Error and eat it.
    }
    else
    {
        throw;
    }
}

解决方案

The mantra is:

You should only catch exceptions if you can properly handle them

Thus:

You should not catch general exceptions.

In your case, yes, you should just catch those exceptions and do something helpful (probably not just eat them--you could throw after you log them).

Your coder is using throw (not throw ex) which is good.

This is how you can catch multiple, specific exceptions:

try
{
    // Call to a WebService
}
catch (SoapException ex)
{
    // Log Error and eat it
}
catch (HttpException ex)
{
    // Log Error and eat it
}
catch (WebException ex)
{
    // Log Error and eat it
}

This is pretty much equivalent to what your code does. Your dev probably did it that way to avoid duplicating the "log error and eat it" blocks.

 
精彩推荐
图片推荐