Java 教程

Java控制語句

面向物件程式設計

Java內建類

Java檔案處理

Java錯誤和異常

Java多執行緒

Java同步

Java網路程式設計

Java集合

Java介面

Java資料結構

Java集合演算法

高階Java

Java雜項

Java APIs和框架

Java類參考

Java有用資源

Java - finally關鍵字



Java finally 關鍵字用於在 Java 程式中定義 finally 塊。Java 中的 finally 塊位於 try 塊或 catch 塊之後。無論 Java 程式中是否發生異常,finally 程式碼塊始終都會執行。

使用 Java finally 塊允許你執行任何你想要執行的清理型語句,無論受保護的程式碼中發生了什麼。

finally 塊出現在 Java 程式中 catch 塊的末尾,並具有以下語法:

語法

try {
   // Protected code
} catch (ExceptionType1 e1) {
   // Catch block
} catch (ExceptionType2 e2) {
   // Catch block
} catch (ExceptionType3 e3) {
   // Catch block
}finally {
   // The finally block always executes.
}

示例

在這個例子中,我們使用無效索引訪問陣列的元素。當程式執行時,它會丟擲 ArrayIndexOutOfBoundsException。由於我們在 catch 塊中處理了此異常,因此也會執行以下 finally 塊。

// File Name : ExcepTest.java
package com.tutorialspoint;

public class ExcepTest {

   public static void main(String args[]) {
      int a[] = new int[2];
      try {
         System.out.println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
      }finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

輸出

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

示例

在這個例子中,我們使用無效索引訪問陣列的元素。當程式執行時,它會丟擲 ArrayIndexOutOfBoundsException。由於我們在catch塊中處理了此異常,並進一步丟擲異常,因此finally塊仍然會被執行。

// File Name : ExcepTest.java
package com.tutorialspoint;

public class ExcepTest {

   public static void main(String args[]) throws CustomException {
      int a[] = new int[2];
      try {
         System.out.println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
         throw new CustomException(e);
      }finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

class CustomException extends Exception{
   private static final long serialVersionUID = 1L;
   CustomException(Exception e){
      super(e);
   }
}

輸出

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Exception in thread "main" First element value: 6
The finally statement is executed
com.tutorialspoint.CustomException: java.lang.ArrayIndexOutOfBoundsException: 3
	at com.tutorialspoint.ExcepTest.main(ExcepTest.java:12)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 3
	at com.tutorialspoint.ExcepTest.main(ExcepTest.java:9)

注意以下幾點:

  • catch 子句不能沒有 try 語句。

  • 並非每次 try/catch 塊都必須有 finally 子句。

  • try 塊不能沒有 catch 子句或 finally 子句。

  • try、catch、finally 塊之間不能有任何程式碼。

java_basic_syntax.htm
廣告
© . All rights reserved.