有沒有人知道是否可以將下面的catch語句塊中的代碼作爲單個語句來編寫代碼?我一直無法想出辦法,只是好奇有沒有辦法。c# - 將catch語句塊中的2條語句合併成一個語句
重要提示:必須保留堆棧跟蹤。
catch (Exception e)
{
if (e is MyCustomException)
{
// throw original exception
throw;
}
// create custom exception
MyCustomException e2 =
new MyCustomException(
"An error occurred performing the calculation.", e);
throw e2;
}
我認爲這與你將要得到的一樣好。你可以首先捕獲MyCustomException,並且只包含一個throw。這也許更標準,但仍然需要兩個「邏輯塊」 – 2009-12-15 16:12:47
是否有一個原因,你不想捕捉,然後在一個單獨的catch中拋出更具體的異常(MyCustomException)?例如:catch(MyCustomException){throw} catch(Exception e){...} – Dexter 2009-12-15 16:17:35
@Dexter - 原因是因爲異常可能已經是MyCustomException。如果是這樣,那麼我不想在另一個MyCustomException中重新包裝它,我只想重新拋出它,但確保保留堆棧跟蹤。 – dcp 2009-12-15 16:19:56