問題描述
我目前正在進行代碼審查,下面的代碼讓我大吃一驚.我看到此代碼存在多個問題.你是否同意我的觀點?如果是這樣,我該如何向我的同事解釋這是錯誤的(固執的類型......)?
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...)?
- 捕獲一個通用異常(Exception ex)
- 使用if (ex is something)"代替另一個 catch 塊
- 我們吃SoapException、HttpException 和WebException.但是,如果 Web 服務失敗了,就沒有什么可做的了.
代碼:
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)是一種不好的做法嗎?為什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!