//我在catch塊如果Catch塊本身發生異常,那麼如何在C#中處理它?
try
{
}
catch(Excepetion ex)
{
// I have written code Here If Exception Occurs here then how to handle it.
}
//我在catch塊如果Catch塊本身發生異常,那麼如何在C#中處理它?
try
{
}
catch(Excepetion ex)
{
// I have written code Here If Exception Occurs here then how to handle it.
}
catch塊是不以任何特定的方式特殊wriiten代碼。您將不得不使用另一個try/catch塊或不處理該錯誤。
try
{
// Some code here
}
catch (Exception ex)
{
try
{
// Some more code
}
catch (Exception ex)
{
}
}
對於可能會在catch
塊中引發異常的代碼行,請使用額外的顯式try..ctach塊。除了考慮有finally
區塊,還有線路在那裏運行。 finally
區塊可能會引發同樣的問題。所以如果你的代碼可能會在finally
塊中拋出一些異常,你也可以在那裏添加try..catch。
try
{
}
catch (Exception ex)
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
finally
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
你可以在catch塊中放一個try catch,或者你可以簡單地拋出異常。其更好有finally塊與您的try catch,以便即使在catch塊中發生異常,最後塊代碼得到執行。
try
{
}
catch(Excepetion ex)
{
try
{
}
catch
{
}
//or simply throw;
}
finally
{
// some other mandatory task
}
最終塊可能不會得到executed in certain exceptions。您可能會看到Constrained Execution Regions以獲得更可靠的機制。
嵌套的try catch語句看起來很糟糕的設計。如果拋出一個異常失敗,你有更大的錯誤來炒。最後總是會發生,所以它是一個糟糕的地方放置代碼,只有當catch語句失敗時纔會發生。我只想吃把手,或者在理想的世界中捕獲所有未處理的異常,這些異常包含try catch塊期間拋出的異常。 –
精心設計的3g編程語言中經常發生雙重錯誤。自從保護模式和286以來,硬件語言的一般設計就是將芯片重置爲三重故障。
你可能確定你的出路是出於雙重故障。不要在這種情況下不得不停止處理/向用戶報告錯誤。如果遇到例如發現IO異常(讀取/寫入數據)然後嘗試關閉正在讀取的流的情況,並且這種情況也會失敗,那麼它不是一個嚴重失敗並且警告的不好的模式用戶發現了一些非常特殊的事情。
感謝所有.. –
我的朋友Atul ..如果你如果在catch塊中寫入try..catch,並且如果在內部try..catch中再次出現異常,那麼同樣的問題會再次出現。 所以解決這個問題,你可以處理在Global.asax中
檢查下面的鏈接,在應用級事件的錯誤..
http://msdn.microsoft.com/en-us/library/24395wz3%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/fwzzh56s%28v=vs.80%29.aspx
讓我知道,如果這對你的作品。 。:)
最好的方法是爲不同的應用程序層開發自己的異常並將其拋出內部異常。它將在應用程序的下一層處理。如果你認爲,你可以在catch塊中得到一個新的異常,只需重新拋出這個異常而無需處理。假設您有兩層:業務邏輯層(BLL)和數據訪問層(DAL),並且在DAL的catch塊中,您有一個例外。
DAL:
try
{
}
catch(Excepetion ex)
{
// if you don't know how should you handle this exception
// you should throw your own exception and include ex like inner exception.
throw new MyDALException(ex);
}
BLL:
try
{
// trying to use DAL
}
catch(MyDALException ex)
{
// handling
}
catch(Exception ex)
{
throw new MyBLLException(ex);
}
有幾個正確答案下面,但我可能會重新考慮我的代碼的設計,以確保不是例外不拋出一個漁獲物,或至少抽象出另一種方法。多個'''try/catch/finally'''塊互相嵌套是一種代碼異味 - 至少在我看來:)。 – Jduv