C# 中 try catch finally 中的流程控制

csharpprogrammingserver side programming更新于 2025/5/26 3:37:17

可以使用以下示例来理解 try、catch 和 finally 中的流程控制。这里,我们将两个数字相除 −

示例

using System;

namespace ErrorHandlingApplication {
   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();
      }
   }
}

输出

Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in :0
Result: 0

以下显示了在 C# 中使用 try catch finally 处理异常时的流程控制

  • 如果 try 块中发生异常,则控制权转移到 catch 块。
  • catch 块完成后,finally 块开始工作。
  • 如果没有发生异常,则首先发生 try,然后流程控制转移到 finally 块

相关文章