即使 Java 的异常块中发生了异常,有没有办法跳过 finally 块?

java 8object oriented programmingprogramming

异常是指程序执行过程中出现的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的代码行之后的代码将永远不会被执行。

Try、Catch、Finally 块

为了处理异常,Java 提供了 try-catch 块机制。

try/catch 块位于可能产生异常的代码周围。try/catch 块内的代码称为受保护代码。

语法

try {
   // 受保护的代码
} catch (ExceptionName e1) {
  // Catch 块
}

当 try 块中引发异常时,JVM 不会终止程序,而是将异常详细信息存储在异常堆栈中,然后继续执行 catch 块。

Catch 语句用于声明要捕获的异常类型。如果 try 块中发生异常,则会将其传递给其后的 catch 块(或多个 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("未找到给定的文件路径");
      }
   }
}

输出

未找到给定的文件路径

Finally 块并跳过它

finally 块位于 try 块或 catch 块之后。finally 代码块始终会执行,无论是否发生异常。您无法跳过 final 块的执行。但是,如果您想在发生异常时强制执行,唯一的方法是在 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

相关文章