在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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP