java捕获不同异常的方式

// 方案1
try {
Class teacherClass = Class.forName(“cn.dongqing.reflect.Teacher”);
Teacher teacher = (Teacher) teacherClass.newInstance();
} catch (IllegalAccessException | ClassNotFoundException | InstantiationException e) {
if (e instanceof IllegalAccessException) {
System.out.println(“非法获取”);
} else if (e instanceof ClassNotFoundException) {
System.out.println(“未找到类”);
}
e.printStackTrace();
}

    // 测试两种异常捕捉的方式
    try {
        Class teacherClass = Class.forName("cn.dongqing.reflect.Teacher");
        Teacher teacher = (Teacher) teacherClass.newInstance();
    } catch (IllegalAccessException e) {
        System.out.println("非法获取");
    } catch (ClassNotFoundException e) {
        System.out.println("未找到类");
    } catch (InstantiationException e) {
        e.printStackTrace();
    }

如果捕获异常后的代码相同,则应采用第一种方式,否则idea会有代码检查提示。

你可能感兴趣的:(java基础知识)