Java-Exception和Error的区别

Exception和Error的区别

继承关系

Exception和Error都继承自Throwable

Throwable的描述:

 * The {@code Throwable} class is the superclass of all errors and
 * exceptions in the Java language. Only objects that are instances of this
 * class (or one of its subclasses) are thrown by the Java Virtual Machine or
 * can be thrown by the Java {@code throw} statement. Similarly, only
 * this class or one of its subclasses can be the argument type in a
 * {@code catch} clause.

只有Throwable的实例才能被JVM抛出或者被Java语句抛出。同时,也只有Throwable以及它的子类能够作为catch块的参数。

Error

Error

 * An {@code Error} is a subclass of {@code Throwable}
 * that indicates serious problems that a reasonable application
 * should not try to catch. Most such errors are abnormal conditions.
 * The {@code ThreadDeath} error, though a "normal" condition,
 * is also a subclass of {@code Error} because most applications
 * should not try to catch it.

应用不应该尝试对Error类进行捕获。

Error一般包括我们不应该捕获的错误,因为就算捕获了之后也无法对错误进行处理,甚至会使JVM处于一个错误的状态,比如OOM错误。

Exception

 * The class {@code Exception} and its subclasses are a form of
 * {@code Throwable} that indicates conditions that a reasonable
 * application might want to catch.

Exception类是应用程序可能会想要捕获的异常。

其中Exception的子类RuntimeException是运行时异常,它属于编译器不进行检查的异常,也就是在任何可能发生该异常的地方,程序可以不进行try..catch..

除了RuntimeException以外,其他的都属于必须捕获或抛出的异常。

猜你喜欢

转载自blog.csdn.net/mingc0758/article/details/80948162
今日推荐