防止异常丢失

来源:互联网 发布:南风知我意 林如斯 编辑:程序博客网 时间:2024/06/05 16:10
一、自定义异常类
public class CustomException extends Exception{      private List<Throwable> list;      public CunstomException(List<? extends Exception>list){           this.list = list;      }       public List<Throwable> getExceptions(){           return list;      }}

二、处理抛异常的函数

// 一个函数同时读取两个文件public void readTwoFile() throws CustomeException {BufferedReader br1 = null;BufferedReader br2 = null;FileReader fr = null;List<Throwable> list = new ArrayList<Throwable>();try {fr = new FileReader("A.txt"); // 1br1 = new BufferedReader(fr);int count = br1.read(); // 2// process code1....fr = new FileReader("B.txt"); // 3br2 = new BufferedReader(fr);count = br2.read(); // 4// process code2} catch (FileNotFoundException ffe) {list.add(ffe); //防止丢弃异常} catch (IOException ie) {list.add(ie);//防止丢弃异常} finally {if (br1 != null) {try {br1.close();} catch (IOException ie) {list.add(ie);//防止丢弃异常}}if (br2 != null) {try {br2.close();} catch (IOException ie) {list.add(ie);//防止丢弃异常}}}// 检查异常的数目if (list.size() > 0)throw new CustomeException(list);}

三、测试端

// 测试客户端public static void main(String[] args) {HideException he = new HideException();try {he.readTwoFile();} catch (CustomeException ce) {List<Throwable>exceptions = ce.getExceptions();
for(int i=0;i<exceptions.size();i++){
                               e = exceptions.get(i);
                               e.printStackTrace();
                        }}}



原创粉丝点击