Java catch内写多个异常

150 阅读1分钟
public class Demo {

    public void test() {

        try {
            throw new NumberFormatException("什么错误");
        } catch (NullPointerException | NumberFormatException e) {
            e.printStackTrace();
            System.out.println("全部异常");
        }
        System.out.println("异常被捕获了");
    }

    public static void main(String[] args) {
        Demo de = new Demo();
        de.test();
    }
}

注意,java7及以上版本才支持

异常类的层级需要相同,同一父类。