Java 异常类介绍 从头(Throwable)说起

Throwable类

Throwable 类是 Java 语言中所有错误或异常的超类。只有当对象是此类(或其子类之一)的实例时,才能通过 Java 虚拟机或者 Java throw 语句抛出。只有此类或其子类之一才可以是 catch 子句中的参数类型。

Throwable 有两个子类: 异常(Exception)、系统错误(Error)

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. TheThreadDeath error, though a "normal" condition, is also a subclass ofError because most applications should not try to catch it. 

Error 是 Throwable 的子类,一个合理的应用程序不应该尝试捕获的严重问题。

Error是程序无法处理的错误,比如OutOfMemoryError、ThreadDeath等。这些异常发生时,Java虚拟机(JVM)一般会选择线程终止。 

Exception

Exception 属于应用程序级别的异常,这类异常必须捕捉,Exception体系包括RuntimeException体系和其他非RuntimeException的体系

Exception 分为未检查异常(RuntimeException)和已检查异常(UnRuntimeException)

运行时异常(RuntimeException)

RuntimeExceptiony 也称为unchecked Exceptiony,不需要try...catch...或throws 机制去处理的异常。在运行是JVM就会抛出异常。

RuntimeRxception类中的注释如下:

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual

Machine.RuntimeException是在Java虚拟机的正常操作期间可以抛出的异常的超类。

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not 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.

RuntimeException及其子类都是未检查的异常。未经检查的异常不需要在方法或构造函数的throws子句中声明,因为可以通过执行方法或构造函数向外抛出未检查异常。此类异常将由JVM进行处理。

总结了一下JAVA中常见的几种RuntimeException:

NullPointerException - 空指针引用异常

ClassCastException - 类型强制转换异常。

IllegalArgumentException - 传递非法参数异常。

ArithmeticException - 算术运算异常

ArrayStoreException - 向数组中存放与声明类型不兼容对象异常

IndexOutOfBoundsException - 下标越界异常

NegativeArraySizeException - 创建一个大小为负数的数组错误异常

NumberFormatException - 数字格式异常

SecurityException - 安全异常

UnsupportedOperationException - 不支持的操作异常

非运行时异常

这里指的是除RuntimeException以外的所有异常。也称为受检异常。

从程序语法角度讲是必须进行处理的异常,如果不处理,程序就不能编译通过。

定义方法时必须声明所有可能会抛出的exception; 在调用这个方法时,必须捕获它的checked exception,不然就得把它的exception传递下去。

猜你喜欢

转载自blog.csdn.net/Jone__/article/details/70885783