这是一个不好的做法来捕获非特定的异常,如System.Exception?为什么? [英] Is this a bad practice to catch a non-specific exception such as System.Exception? Why?
问题描述
我正在进行代码审查,以下代码让我跳。我看到这个代码有多个问题。你是否同意我的观点?如果是这样,我怎么向同事解释这是错误的(顽固的类型...)?
- 捕捉一般异常(异常
- 使用if(ex is something)而不是另一个catch块
- 我们吃了SoapException,HttpException和WebException。但是如果Web服务失败,那么没有太多的事情要做。
代码:
try
{
//调用WebService
}
catch(Exception ex)
{
如果(ex是SoapException || ex是HttpException || ex是WebException)
{
//记录错误并吃掉它。
}
else
{
throw;
}
}
咒语是:
- 如果
您可以正确处理,您应该只捕获异常 - 您不应该捕获一般的
异常。
因此:
在你的情况下,是的,你应该只是捕获这些异常并做一些有用的事情(可能不只是吃了他们 - 你可以在你登录后可以 throw
。
你的编码器正在使用 throw
(不是 throw ex
)这是 。
这是你可以捕捉多个具体的例外:
try
{
//调用WebService
}
catch(SoapException ex)
{
//记录错误并吃它
}
catch(HttpException ex)
{
//记录错误并吃它
}
catch(WebException ex)
{
//记录错误并吃它
}
这几乎等同于你的代码。你的开发者可能这样做,以避免重复日志错误并吃掉它的块。
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屋!