一、自定义异常类
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"); // 1
br1 = new BufferedReader(fr);
int count = br1.read(); // 2
// process code1....
fr = new FileReader("B.txt"); // 3
br2 = 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();
}
}
}