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.