Exception
异常分类
父类 throwable
两个子类 Exception Error
Error 列入宕机比较大的异常 无法处理 标识有error
Exception
分为运行时异常和编译时异常
常见异常
NullPointerException 空指针 对象引用为null调用方法
IndexOutOfBoundsException 索引越界异常 超出索引范围
ClassNotFoundException 找不到类异常
ClassCastException 类型转换异常
FileNotFoundException 找不到文件异常
IOException IO流异常
处理异常的两个方式
try-catch-finally
1 | try{ |
2 | int a = 10; |
3 | int b = 0; |
4 | System.out.println(a/b); |
5 | }catch(ArithmeticException e){ |
6 | e.printStackTrace(); |
7 | }finally{ |
8 | System.out.println("这里一定执行"); |
9 | } |
finally 是可有的 里面代码一定执行 常用于关闭流,链接之类的
fanal修饰类 类不能被继承 修饰方法 方法不能被重写 修饰变量 为常量
finanize是Object类的方法 用于垃圾回收处理对象用的
throws
声明在方法上 用于声明异常类型 用调用者处理异常
1 | public void test() throws ArithmeticException{ |
2 | int a = 10; |
3 | int b = 0; |
4 | System.out.println(a/b); |
5 | } |
throw
用于生成一个异常对象 在方法体内
如果有多个方法递进调用 在前面的方法用throws 最后方法使用try-catch处理