Java 的 code form 到底会不会阻塞
finally 块紧接在 try 块或 catch 块后面。无论是否发生异常,finally 块内的代码始终都会执行。
方法中的 return 语句也不会阻止 finally 块执行。
示例
在以下 Java 程序中,我们仍然在 try 块末尾使用 return 语句,finally 块中的语句会执行。
public class FinallyExample {
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
return;
} 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
避免 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP