問(wèn)題描述
我目前正在進(jìn)行代碼審查,下面的代碼讓我大吃一驚.我看到此代碼存在多個(gè)問(wèn)題.你是否同意我的觀點(diǎn)?如果是這樣,我該如何向我的同事解釋這是錯(cuò)誤的(固執(zhí)的類(lèi)型......)?
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...)?
- 捕獲一個(gè)通用異常(Exception ex)
- 使用if (ex is something)"代替另一個(gè) catch 塊
- 我們吃SoapException、HttpException 和WebException.但是,如果 Web 服務(wù)失敗了,就沒(méi)有什么可做的了.
代碼:
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;
}
}
推薦答案
口頭禪是:
- 您應(yīng)該只在以下情況下捕獲異常你可以妥善處理它們
因此:
- 你不應(yīng)該抓住一般例外.
在您的情況下,是的,您應(yīng)該只捕獲這些異常并做一些有用的事情(可能不僅僅是吃掉它們——您可以在記錄它們之后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.
這是您可以捕獲多個(gè)特定異常的方法:
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
}
這幾乎等同于您的代碼所做的.您的開(kāi)發(fā)人員可能這樣做是為了避免重復(fù)記錄錯(cuò)誤并吃掉它"塊.
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.
這篇關(guān)于捕獲非特定異常(例如 System.Exception)是一種不好的做法嗎?為什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!