C# 中的 finally 關鍵字


finally 關鍵字用作塊以執行給定的一組語句,無論是否丟擲異常。例如,如果您開啟一個檔案,無論是否引發異常都必須關閉它。

語法

以下是語法:

try {
   // statements causing exception
} catch( ExceptionName e1 ) {
   // error handling code
} catch( ExceptionName e2 ) {
   // error handling code
} catch( ExceptionName eN ) {
   // error handling code
} finally {
   // statements to be executed
}

示例

讓我們看一個實現 finally 塊的示例:

 即時演示

using System;
public class Demo {
   int result;
   Demo() {
      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);
      }
   }
   public static void Main(string[] args) {
      Demo d = new Demo();
      d.division(100, 0);
   }
}

輸出

這將產生以下輸出:

Exception caught = System.DivideByZeroException: Attempted to divide by zero.
   at Demo.division(Int32 num1, Int32 num2) in d:\Windows\Temp
0kebv45.0.cs:line 11 Result = 0

更新於: 11-12-2019

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始行動
廣告