我寫了簡單的C#控制檯應用程序:異常拋出catch和最後。 CLR行爲與try-catch塊
class Mystery
{
static void Main(string[] args)
{
MakeMess();
}
private static void MakeMess()
{
try
{
System.Console.WriteLine("try");
throw new Exception(); // let's invoke catch
}
catch(Exception)
{
System.Console.WriteLine("catch");
throw new Exception("A");
}
finally
{
System.Console.WriteLine("finally");
throw new Exception("B");
}
}
}
控制檯給出的輸出是:
嘗試
抓
未處理的異常: System.Exception:A在Mystery.Program.MakeMess()in ...
看來,CLR抓到了A並且finally塊沒有被調用。
但是,當我周圍調用MakeMess()的try-catch塊:
static void Main(string[] args)
{
try
{
MakeMess();
}
catch(Exception ex)
{
System.Console.WriteLine("Main caught " + ex.Message);
}
}
輸出看起來完全不同:
嘗試
抓
終於
Main被捕獲B
當Exception嚴格在方法外部處理時,從MakeMess()傳播的異常看起來不同。
這種行爲的解釋是什麼?
如果你在編譯器之外運行,會發生什麼?我認爲最後會寫成 – TheLethalCoder
請參閱http://stackoverflow.com/a/1555578/613130 *一個重要的注意事項是,如果e未被try/catch塊捕獲到進一步向上調用堆棧或由全局處理異常處理程序,那麼finally塊可能永遠不會執行。* – xanatos
你沒有捕獲異常。程序停止。當某些事情完全失敗時沒有理由繼續。在你的秒示例中,它與嵌套try catch相同。外部嘗試將捕獲內部捕獲的異常。但在此之前最終會被調用。 –