代码是否构成 Java finally 块
java 8object oriented programmingprogramming更新于 2025/11/20 20:28:17
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

