Java中的异常
程序错误一般分为三种:
编译错误: 编写程序时没有遵循语法规则,编译程序能够自己发现错误并提示位置和原因。
运行错误:程序在执行的时候运行环境发现了不能执行的操作。比如,JVM出错了,内存溢出等。
逻辑错误:程序没有按照预期的逻辑顺序执行。比如,在四则运算中除数不能为零,数组下标越界,空指针异常等。
异常继承结构:
Throwable 是 Java 语言中所有错误或异常的超类。
下一层分为 Error 和 Exception 。Exception 又有两个分支
一个是运行时异常 RuntimeException ,一个是CheckedException。
RuntimeException 如 : NullPointerException 、 ClassCastException等;
CheckedException 是受查异常,如 I/O 错误导致的 IOException、SQLException。
RuntimeException 是那些可能在 Java 虚拟机正常运行期间抛出的异常的超类。
如果出现 RuntimeException,那么一定是程序员的错误.


Error:错误,无法被处理的
Exception:异常,能够被程序本身处理的,可以通过try…catch语句捕捉异常,或者是throws抛出异常。分为运行时异常和非运行时异常。
运行时异常:就是RuntimeException,编译时不会检查出错误的。一般是由于逻辑错误引起的,程序员可以手动去解决的,比如判空等。
非运行时异常:也叫编译异常,就是Exception下除了RuntimeException以外的异常。是必须进行处理的异常,编译器会进行异常提醒的。如果不进行处理,程序编译不通过。
Throwable中java的异常一般分为受查异常和非受查异常:

受查异常:编译器报错。Exception下除了RuntimeException以外的都是受查异常。这种异常都发生在编译阶段,Java 编译器会强制程序去捕获此类异常。

非受查异常:运行时报错。非受查异常包括Error和RuntimeException。RuntimeException表示编译器不会检查是否对RuntimeException进行了处理,在程序中不必去捕获RuntimeException异常,也不必在方法体抛出RuntimeException异常类。RuntimeException发生就说明程序出现了编程错误,应该找出错误去修改,而不是去捕获异常。

异常处理方式:
捕捉异常:常用的try…catch模式

声明异常:常用的throws模式

异常与方法重写:
子类声明异常的范围不能超过父类声明的范围
父类没有声明异常,子类也不能
自定义异常:
创建类
继承Exception或者Exception的子类
重写构造方法


Throw 和 throws 的区别:
throws 用在函数上,后面跟的是异常类,可以跟多个;而 throw 用在函数内,后面跟的
是异常对象。
throws 用来声明异常,让调用者只知道该功能可能出现的问题。throw 抛出具体的问题对象,执行到 throw,功能就已经结束了,跳转到调用者,并将具体的问题对象抛给调用者。也就是说 throw 语句独立存在时,下面不要定义其他语句,因为执行不到。