在异常处理过程中,有时候,我们希望无论try块中的异常是否抛出,他们都能够得到执行。这通常适用于内存回收之外的情形。
为了达到这样的效果,可以在异常处理程序后面加上finally子句。
下面这个程序证明了finally子句总是能够运行:
class ThreeException extends Exception{}
public class FinallyWorks {
static int count = 0;
public static void main(String[] args) {
while(true) {
try {
// Post-increment is zero first time:
if(count++ == 0)
throw new ThreeException();
System.out.println("No exception");
}catch(ThreeException e) {
System.out.println("ThreeException");
}finally {
System.out.println("In finally clause");
if(count == 2)break; // out of while
}
}
}
}
运行结果:
我们可以看到这段程序中,无论异常是否被抛出,finally子句总能被执行。