异常基础
Error
Error是Throwable的子类,这代表了Java程序运行过程中的一种未知原因的错误,当程序运行遇到Error的时候,不应该在代码中捕获。跟运行时异常(RuntimeException)一样,Java代码中的方法签名中不应该声明任何Error的子类。
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a “normal” condition, is also a subclass of Error because most applications should not try to catch it.
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.
Exception
Exception也是Throwable的子类,这种运行时的异常情况,是可以在程序中捕获并进行处理的。异常中的运行时异常(RuntimeException)是Exception的子类,又称为非受检异常——如果在某个方法中抛出运行时异常,无需在该方法签名上声明运行时异常。
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor’s throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

开发中的异常使用原则
- 捕获异常的时候,必须打印日志堆栈,并且抛出异常,不能默默地吞掉异常
- 异常属于一种方法调用的返回方式,正常的结果通过返回值返回,所有异常情况都通过受检异常进行返回,并设定自定义的异常码和消息,这是一种统一的方法调用方式。
面试题
问题1:请对比 Exception 和 Error,运行时异常与一般异常有什么区别?
- Exception和Error提现了Java平台的设计者对程序错误的两种分类。Error是指平台级别的错误,如果发生某种xxxxError,则表示JVM虚拟机出现了不可回复的错误,例如OutOfMemoryError;Exception则表示程序级的错误,在发现异常的时候,可以通过catch异常来让程序继续运行,例如NullPointException。
- Exception又分为受检异常和非受检异常,受检异常是指如果一个方法中如果抛出某个受检异常,则该异常必须声明在方法签名上;非受检异常则不需要声明在方法上。非受检异常就是运行时异常。
问题2:NoClassDefFoundError和ClassNotFoundException有啥区别?
- NoClassDefFoundError是Error的子类,属于不可捕获的错误;ClassNotFoundException属于一般异常,可以在方法声明并捕获
- NoClassDefFoundError:编译的时候可以编译成功,但是当JVM在运行时尝试加载一个类的时候,但是没有找到这个类的定义,这时候会抛出NoClassDefFoundError;
- ClassNotFoundException:当应用程序运行的过程中尝试使用类加载器去加载Class文件的时候,如果没有在classpath中查找到指定的类,就会抛出ClassNotFoundException,主要是下面三个方法可能抛出ClassNotFoundException
- Class.forName()
- ClassLoader.loadClass
- ClassLoader.findSystemClass()
