如何在 C# 中使用 Try/catch 塊?


異常提供了一種將控制從程式的一處轉移到另一處的方法。C# 異常處理基於四個關鍵字構建:try、catch、finallythrow

  • try − try 塊識別用於啟用特定異常的程式碼塊。其後面緊跟一個或多個 catch 塊。

  • catch − 程式透過異常處理程式捕獲異常,該異常處理程式位於程式中需要處理問題的位置。catch 關鍵字表示正在捕獲異常。

以下是顯示如何在 C# 中使用 try、catch 和 finally 的示例。

示例

 線上演示

using System;
namespace Demo {
   class DivNumbers {
      int result;
      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}

輸出

Result: 0

更新於: 2020 年 6 月 23 日

2K+ 瀏覽量

開啟您的 職業

完成課程後獲得認證

開始
廣告