这是一个不好的做法,赶上非特异性异常如System.Exception的?为什么? [英] Is this a bad practice to catch a non-specific exception such as System.Exception? Why?

查看:232
本文介绍了这是一个不好的做法,赶上非特异性异常如System.Exception的?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

code:

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

解决方案

的口头禅是:

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

这样:

  • 您不应该赶上一般 异常。


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

您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.

这篇关于这是一个不好的做法,赶上非特异性异常如System.Exception的?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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