連結異常是一系列處理例外的try-catch語句。要建立異常鏈,即連結異常−
設定第一個try-catch −
static void Main(string[] args) { try { One(); } catch (Exception e) { Console.WriteLine(e); } }
現在在方法One()下嘗試使用try-catch −
static void One() { try { Two(); } catch (Exception e) { throw new Exception("First exception!", e); } }
方法Two()也會繼續鍊式例外。
static void Two() { try { Three(); } catch (Exception e) { throw new Exception("Second Exception!", e); } }
現在是下一個方法。
static void Three() { try { Last(); } catch (Exception e) { throw new Exception("Third Exception!", e); } }
The takes us to the last.
static void Last() { throw new Exception("Last exception!"); }
在執行上述程式碼時,例外會被處理如下−
System.Exception: First exception! ---< System.Exception: Middle Exception! ---< System.Exception: Last exception! at Demo.Two () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0 --- End of inner exception stack trace --- at Demo.Two () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0 at Demo.One () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0 --- End of inner exception stack trace --- at Demo.One () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0 at Demo.Main (System.String[] args) [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0
以上是C# 中的鍊式異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!