初探Java的异常体系

1.Exception和Error的区别
Exception和Error都继承了Throwable,只有throwable类型的异常才能被throw或catch。
Exception是程序在运行过程中可以预料的意外情况,需要进行捕捉并进行相应的处理。
Error是程序在运行过程中不可以预料的错误,不便于也不需要处理,绝大部分Error都会导致程序异不可恢复,如:OutOfMemoryError。
Exception可分为检查异常和不检查异常,其中检查异常需要我们显式进行捕捉(如IOException),因为这是编译期检查的一部分;不检查异常就是我们常说的运行时异常,通常是编码可以避免的逻辑错误,如NullpointerException,可以根据实际情况进行适当的处理。


2.异常处理的两个基本原则
尽量不要捕捉类似Exception这类的通用异常,而是捕捉特定的异常;
不要生吞异常,否则程序意外出错,我们无法跟踪和定位;

3.测试demo

/**
 * 可检查异常测试类
 */
public class CheckedExceptionTest {
    public static void main(String[] args) {
        File file = new File("/e/test_file");
        try {
            file.createNewFile();//操作文件的方法,抛出了IOException
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public boolean createNewFile() throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) security.checkWrite(path);
    if (isInvalid()) {
        throw new IOException("Invalid file path");
    }
    return fs.createFileExclusively(path);
}

/**
 * 不可检查异常(运行时异常,如NullPointerException)测试类
 */
public class UnCheckedExceptionTest {
    public static void main(String[] args) {
        String name = null;
        System.out.println(name.toString());//这里应为调用了String对象的方法,但是String对象为null,会抛出一个NullPointerException异常。
    }
}

4.NoClassDefFoundError和ClassNotFoundException有什么区别?
ClassNotFoundException继承Exception,是一个可检查异常。当程序在运行过程中,类加载器尝试去加载class的时候,如果在classpath中没有找到指定的类,程序就会抛出ClassNotFoundException。
可能导致该异常的使用场景:
Class.forName()
ClassLoader.loadClass
ClassLoader.findSystemClass()
实际应用场景:使用JDBC连接数据库的时候,我们会使用Class.forName去获取驱动,如果classpath下面没有找到对应的驱动,程序就会抛出ClassNotFoundException。

NoClassDefFoundError继承Error。当编译成功后,在程序执行过程中找不到类的时候会出现该错误,由JVM的运行时系统抛出。

5.自定义异常
我们为什么要使用自定义异常?程序内部可能抛出各种各样的异常,为了统一异常对外的展现方法,我们就需要使用自定义异常。
如何自定义异常呢?一般我们直接继承RuntimeException类。
比如我们现在需要统一抛出业务中的错误,就可以定义一个统一的业务异常,如下所示:
public class CommonBizException extends RuntimeException {
    private static final long serialVersionUID = -2157507876189274583L;

    public CommonBizException(String msg) {
        super(msg);
    }
}

在需要抛出业务异常的地方这么使用:
throw new CommonBizException(msg);

猜你喜欢

转载自blog.csdn.net/weixin_39283212/article/details/89508298
今日推荐