一、什么是异常?
异常指程序运行中出现的不期而至的各种状况,如:文件找不到、网络连接失败、非法参数等。
异常发生在程序运行期间,它影响了正常的程序执行流程。
二、异常的分类
①:Throwable:java中的所有错误和异常的父类,位于Java.lang包中
②:Error 代表错误,代表产生了无法靠程序本身恢复的严重错误
③:Exception 代表异常
异常又分为RuntimeException和非RuntimeException;
RuntimeException:运行时异常,可编译不可运行,此类异常可以避免,可处理也可不处理,不处理可以通过严谨代码避免
非RuntimeException:非运行时异常,不可编译不可运行,必须处理
注意:编译报错的两个原因:
I. 检测语法是否正确
II . 存在在非运行异常
三、异常的处理
①:积极处理(捕获并抛出异常):只能定义在方法内部
语法:
try{
// 可能出现异常的语句
}catch(异常类名 e){
// 异常出现时,执行的语句
}finally{
// 不管有没有异常一定执行的语句
}
②:消极处理(只声明异常即可):写在方法·声明部分
使用消极处理可以让非运行时异常编译通过
语法
修饰符 返回值类型 方法名(形参)throws 异常类名1,异常类名2{}
③异常处理的关键字:try、catch、finally、throw、throws
四、自定义异常
在程序中使用自定义异常类,大体可分为以下几个步骤:
创建自定义异常类
在方法中通过throw关键字抛出异常对象。
如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常,继续进行下一步操作。
在出现异常方法的调用中捕获并处理异常。
如果自定义异常类直接继承了Exception,则为非运行时异常
如果自定义异常类直接继承RuntimeException或是其子类,则为运行时异常
例子
public class Test1 {
public static void main(String[] args)throws Exception {
System.out.println("main----start-----1");
m1(6);
System.out.println("main----end-----2");
}
public static void m1(int n)throws Exception{
System.out.println("main----start-----3");
m2(n);
System.out.println("main----end-----4");
}
public static void m2(int n)throws ClassNotFoundException, EOFException,Exception,FileNotFoundException {
System.out.println("main----start-----5");
//手动创建异常
if(n==1) throw new RuntimeException("程序因不可名状而终止~~~~~");
if(n==2) throw new ClassNotFoundException();
if(n==3) throw new Exception("程序因不可名状而终止~~~~~");
if(n==4) throw new FileNotFoundException("程序因不可名状而终止~~~~~");
System.out.println("m2```m3,,,m4");
}
}
输出结果为
main----start-----1
main----start-----3
main----start-----5
m2```m3,,,m4
main----end-----4
main----end-----2
同时子类不能抛出比父类更宽的
总结:常见的异常处理结构
try{}catch(){}
try{}catch(){}catch(){}
try{}catch(){}catch(){}finally{}
try{}finally{} ->目的不是处理异常,而是为了一些必须执行的语句,定义在finally中
注意:try不能单独使用,后面需要跟catch或是finally{}
try{ try{}catch(){} }catch(){}
try{}catch(){ try{}catch(){} }
try{}catch(){}finally{ try{}catch(){} }