
实际开发中当一个功能需要借助很多子模块合并处理,各子模块抛出的异常不同且无需关心(或仅仅需要关注其中的几种)异常类型,有如下两种方法:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test01 {
/**
* 多个异常同时catch
* @param args
*/
public static void main(String[] args) {
try {
Class.forName("java.lang.String");
new FileInputStream("demo.txt");
}catch (ClassNotFoundException | FileNotFoundException e) {
// 第一种方式,直接将两种异常放到一个catch中处理
e.printStackTrace();
System.out.println("干点啥的时候发生了异常,但是又不想对外公开,可以合并处理");
}catch (Exception e) {
// 第二种方式,使用他们的父类进行捕获,然后根据类型去处理
e.printStackTrace();
if(e instanceof ClassNotFoundException) {
System.out.println("ClassNotFoundException");
}else if(e instanceof FileNotFoundException) {
System.out.println("FileNotFoundException");
}else {
System.out.println("Other Exception:" + e.getClass().getName());
}
}
}
}