C# 中 try catch finally 的流控制


下面这个例子有助于理解 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 块

更新于: 22-Jun-2020

574 次观看

启动你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.