我目前正在进行代码审查,下面的代码让我大吃一惊.我看到此代码存在多个问题.你是否同意我的观点?如果是这样,我该如何向我的同事解释这是错误的(固执的类型......)?
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...)?
代码:
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;
}
}
口头禅是:
因此:
在您的情况下,是的,您应该只捕获这些异常并做一些有用的事情(可能不仅仅是吃掉它们——您可以在记录它们之后throw
).
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).
您的编码器正在使用 throw
(不是 throw ex
),这是 好.
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)是一种不好的做法吗?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!