构造方法中的异常清理

在构造方法中对“受检查异常”的处理可以使用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);
            }
      }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值