目录
什么是异常
异常就是程序的运行过程中所发生的不正常的事件
例如:算术运算出错、数组下标越界等
异常处理
异常处理五个关键字:try、catch、finally、throw 和 throws
1、try-catch 块
情况1:try块正常执行,不执行catch块
情况2:try块发生异常,执行catch块
常见的异常类型
异常 | 说明 |
Exception | 异常层次结构的根类 |
ArithmeticException | 算术错误情形 |
ArrayIndexOutOfBoundsException | 数组下标越界 |
NullPointerException | 尝试访问null对象成员 |
ClassNotFoundException | 不能加载所需的类 |
InputMismatchException | 欲得到的数据类型与实际输入的类型不匹配 |
IllegalArgumentException | 方法接收到非法参数 |
ClassCastException | 对象强制类型转换出错 |
NumberFormatException | 数字格式转换异常 |
2、try-catch-finally 块
无论是否发生异常,finally块中的代码都执行
finally块中语句不被执行的唯一情况:在异常处理代码中执行System.exit(1);
声明异常——throws
通过try-catch捕获并处理异常
通过throws声明异常,让上一级调用者处理异常,main()方法声明的异常由java虚拟机处理
throws Exception
抛出异常——throw
throw关键字自行抛出异常
throw new Exception("抛出异常");