仅作为学习记录。
1. Exception ,Exception 作为 异常类的顶层接口。合理的Java应用程序应该想要捕获 Exception(含其子类),Exception 继承自(is-a)Throwable。
/**
* The class {@code Exception} and its subclasses are a form of
* {@code Throwable} that indicates conditions that a reasonable
* application might want to catch.
*
* <p>The class {@code Exception} and any subclasses that are not also
* subclasses of {@link RuntimeException} are <em>checked
* exceptions</em>. Checked exceptions need to be declared in a
* method or constructor's {@code throws} clause if they can be thrown
* by the execution of the method or constructor and propagate outside
* the method or constructor boundary.
*
* @author Frank Yellin
* @see java.lang.Error
* @jls 11.2 Compile-Time Checking of Exceptions
* @since JDK1.0
*/
public class Exception extends Throwable {
从第二段注释中,我们可以看到。CheckedException 是 Exception 的子类,但不是 RuntimeException 的子类。CheckedException 需要声明在 方法或者构造器 的抛出异常语句部分( public void methodA() throws xxx ),从而在方法或构造器 执行出现异常时,传播到 该方法或构造器 之外。
2. RuntimeException 运行异常,JVM 执行中会抛出 一系列 运行时异常(或者其子类)。
/**
* {@code RuntimeException} is the superclass of those
* exceptions that can be thrown during the normal operation of the
* Java Virtual Machine.
*
* <p>{@code RuntimeException} and its subclasses are <em>unchecked
* exceptions</em>. Unchecked exceptions do <em>not</em> need to be
* declared in a method or constructor's {@code throws} clause if they
* can be thrown by the execution of the method or constructor and
* propagate outside the method or constructor boundary.
*
* @author Frank Yellin
* @jls 11.2 Compile-Time Checking of Exceptions
* @since JDK1.0
*/
public class RuntimeException extends Exception {
从第二段注释中,我们可以知道。Unchecked Exception 包含 RuntimeException 及其子类。Unchecked Exception 不需要在 方法或构造器 上声明异常抛出的原因( public void methodA() {} ),从而在 该方法或构造器 执行出现异常时,传播到 该方法或构造器 之外。
Java 定义了两种异常:
- Checked exception: 继承自 Exception 类是 checked exception。代码需要处理 API 抛出的 checked exception,要么用 catch 语句,要么直接用 throws 语句抛出去。
- Unchecked exception: 也称 RuntimeException,它也是继承自 Exception。但所有 RuntimeException 的子类都有个特点,就是代码不需要处理它们的异常也能通过编译,所以它们称作 unchecked exception。RuntimeException(运行时异常)不需要try...catch...或throws 机制去处理的异常。
NullpointerException 的继承级别。
NullpointerException 继承自 RuntimeException,所以它是个 unchecked exception。
最常用的五种RuntimeException:
ArithmeticException | int a=0; |
ClassCastException: | Object x = new Integer(0); |
IndexOutOfBoundsException | int [] numbers = { 1, 2, 3 }; |
IllegalArgumentException | int a = Interger.parseInt("test"); |
NullPointerExceptionextends |
|
小结:
检查性异常: 不处理编译不能通过
非检查性异常:不处理编译可以通过,如果有抛出直接抛到控制台。
运行时异常: 就是非检查性异常
非运行时异常: 就是检查性异常
参考 https://blog.csdn.net/xjbclz/article/details/53151552