在Java中,有沒有辦法即使異常塊中發生某些異常也能跳過finally塊?
異常是在程式執行期間發生的錯誤(執行時錯誤)。當發生異常時,程式會突然終止,並且異常行之後的程式碼永遠不會執行。
Try、catch、finally 塊
為了處理異常,Java 提供了 try-catch 塊機制。
try/catch 塊放置在可能生成異常的程式碼周圍。try/catch 塊內的程式碼稱為受保護程式碼。
語法
try { // Protected code } catch (ExceptionName e1) { // Catch block }
當 try 塊內部引發異常時,JVM 不會終止程式,而是將異常詳細資訊儲存在異常堆疊中,並繼續執行 catch 塊。
catch 語句涉及宣告您嘗試捕獲的異常型別。如果 try 塊中發生異常,它將傳遞給其後的 catch 塊(或塊)。
如果發生的異常型別在 catch 塊中列出,則異常將傳遞給 catch 塊,就像引數傳遞給方法引數一樣。
示例
import java.io.File; import java.io.FileInputStream; public class Test { public static void main(String args[]){ System.out.println("Hello"); try{ File file =new File("my_file"); FileInputStream fis = new FileInputStream(file); }catch(Exception e){ System.out.println("Given file path is not found"); } } }
輸出
Given file path is not found
Finally 塊和跳過它
finally 塊位於 try 塊或 catch 塊之後。無論是否發生異常,finally 塊中的程式碼始終都會執行。您無法跳過 finally 塊的執行。但是,如果您希望在發生異常時強制執行此操作,唯一的方法是在 catch 塊的末尾(緊接在 finally 塊之前)呼叫 System.exit(0) 方法。
示例
public class FinallyExample { public static void main(String args[]) { int a[] = {21, 32, 65, 78}; try { System.out.println("Access element three :" + a[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); System.exit(0); } 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: 5
廣告