即使使用Java在异常块中发生了某些异常,是否有任何方法可以跳过finally块?

例外是程序执行期间发生的问题(运行时错误)。当发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。

尝试,抓到,最后阻止

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

在可能产生异常的代码周围放置了一个try / catch块。try / catch块中的代码称为受保护代码。

语法

try {
   //受保护的代码
} catch (ExceptionName e1) {
   //渔获
}

当在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块位于try块或catch块之后。无论是否发生异常,始终都会执行一个finally代码块。您不能跳过最后一个块的执行。仍然,如果您想在发生异常时强行执行此操作,唯一的方法是在catch块的末尾,即finally块之前,调用System.exit方法。

示例

public class FinallyExample {
   public static void main(String args[]) {
      int a[] = {21, 32, 65, 78};
      try {
         System.out.println("访问元素三:" + a[5]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("抛出异常:" + 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