C# 中 finally 语句是什么?


最终块用于执行一组给定的语句,无论是否引发了异常。例如,如果你打开了一个文件,那么无论是否引发了异常,都必须关闭该文件。

错误处理块是使用 try、catch 和 finally 关键字实现的。

示例

你可以尝试运行以下代码来实现 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();
      }
   }
}

更新日期:2020 年 6 月 20 日

282 次浏览

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.