C# 中的鏈式異常


鏈式異常是一系列用於處理異常的 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);
   }
}

使我們進入最後一個方法。

示例

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

更新於: 22-Jun-2020

495 次瀏覽

開始你的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.