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

csharpprogrammingserver side programming更新于 2025/7/10 14:07:17

异常提供了一种将控制权从程序的一部分转移到另一部分的方法。C# 异常处理基于四个关键字:try、catch、finally 和 throw。

  • 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

相关文章