Java异常处理首先是指程序在运行期间产生的异常而非编译期间,抛出了异常后,观察异常的名字以及行号及其重要。

1、异常的分类:首先Java的异常都可以Throwable,其中包含Error和Exception,Error一般我们处理不了,在Exception下面又有常见的Runtime Exception。

所以对于出了Runtime Exception(可以处理,也可以不处理)之外的所有Exception,我们都必须进行显示地进行捕获。
2、五个关键字:try、catch、finally、throw、throws。



throw是语句抛出一个异常。(用于方法里)
语法:throw (异常对象);
throw e;
throws是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常)
语法:[(修饰符)](返回值类型)(方法名)([参数列表])[throws(异常类)]{......}
public void doA(int a) throws Exception1,Exception3{......}
throws出现在方法函数头;而throw出现在函数体。
throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常。
3、在catch异常时,先逮范围小的异常,再逮范围大的异常。(比如FileNotFoundException属于IOException,所有必须先catch范围小的,不然编译会出错。)
4、重写方法需要抛出与原方法所抛出异常类型一致或者不抛出异常。(如果异常类型不一样,编译会报错。)

网友评论