在构造方法中对“受检查异常”的处理可以使用finally块来完成清理工作。但是并不是每次初始化对象的时候都会有异常被抛出,所以应该设置一个标志,来判断finally块中的语句是否真的要被执行。但是这种方法属于“Trick”,并不提倡使用。还有一种方法是在捕获到异常的catch块中来完成清理工作。
下面这个例子的构造方法的清理工作是指“关闭被打开的文件(如果文件被打开的话)”
//ConstructorException.java
//paying attention to the exceptions thrown form constructor.
package com.msn.spaces.bryantd001;
import java.io.*;
class InputFile{
private BufferedReader in;
InputFile(String fname) throws Exception{
try{
in = new BufferedReader(new FileReader(fname));
//other code that might throw exception
//throw new Exception("Another Exception.");
}catch(FileNotFoundException eOpenFile){
System.err.println("File not found!");
//在这里不用完成清理工作,因为文件根本就没有被打开
//将“文件没有被打开”异常再次抛出,交给上层容器处理
throw eOpenFile;
}catch(Exception eOther){
//如果程序抛出的异常在这个catch块中被捕获,说明文件已经打开,而异常是由后面的代码抛出的
//因此文件必须被关闭(文件不再可用)
//由于“关闭文件”操作也可能抛出IO异常,所以要放在try块中进行处理
try{
in.close();
}catch(IOException eClose){
System.err.println("File cannot be closed.");
//如果关闭文件异常,则交由上层容器处理
throw eClose;
}
//将非文件打开异常交由上层容器处理
throw eOther;
}
}
InputFile(String fname, String msg) throws Exception{
boolean fileOpen = true; //设置一个标志位
try{
in = new BufferedReader(new FileReader(fname));
//other code that might throw exception
//throw new Exception("Another Exception.");
}catch(FileNotFoundException eOpenFile){
System.err.println("File not found!");
//若文件没有打开,则设置标志位,使finally块中的清理语句发挥作用
fileOpen = false;
throw eOpenFile;
}catch(Exception eOther){
throw eOther;
}finally{
if (fileOpen){
try{
in.close();
}catch(IOException eClose){
System.err.println("File cannot be closed.");
throw eClose;
}
}
}
}
public void dispose(){
try{
in.close();
System.out.println("File is closed successfully!");
}catch(IOException eIO){
//将“受检查异常”封装为“不受检查异常”(运行时异常)可以简化异常处理
//这样做之后就不必必须在异常声明中列出异常,或者利用catch块捕获处理异常了
System.out.println("File cannot be closed");
throw new RuntimeException(eIO);
}
}
}
public class ConstructorException{
public static void main(String[] args){
try{
//InputFile in = new InputFile("ConstructorException.java");
InputFile in = new InputFile("ConstructorException.java" , "Using the 2ed constructor.");
System.out.println("File is opened successfully!");
System.out.println("Do sth about the file……");
in.dispose();
}catch(Exception e){
System.out.println("Exception is caught in the main()!!");
System.out.println(e);
}
}
}