什么是 C# 中的 finally 语句?


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

使用 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();
      }
   }
}

更新于: 20-6 月-2020 年

282 次查看

开启你的职业生涯

完成课程并获得认证

开始学习
广告
© . All rights reserved.