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("访问元素三:" + a[3]);
return;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("抛出异常:" + e);
} finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}输出结果
抛出异常:java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
仍然,如果您想在发生异常时强行执行此操作,唯一的方法是在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");
}
}
}输出结果
抛出异常:java.lang.ArrayIndexOutOfBoundsException: 5