Java基础知识总结复盘之异常
保证程序健壮性的一个重要因素就是异常。
异常体系
程序中一切不正常的事件都称为异常。
异常分为:错误(Error) 和 异常(Exception)
错误的解决有两种方式:改机器配置或修改源码
Exception in thread "main" java.lang.StackOverflowError
at com.edu.day0720.excep.ExceptionTest.method1(ExceptionTest.java:9)
at com.edu.day0720.excep.ExceptionTest.method1(ExceptionTest.java:9)
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.edu.day0720.excep.ExceptionTest.main(ExceptionTest.java:7)
Throwable是 Error和Exception的父类
Exception的子类型分类:
一类是运行时异常(只要是 RuntimeException的子类型都是运行时异常)
一类编译异常(不是RuntimeException子类型)
运行时异常也称为非受检异常,可以不处理编译也可以通过
编译异常称为受检异常,必须要处理后编译才可以通过
异常处理
抓异常
使用语法:try..catch..finally
1,try{ 代码块}
- 有可能出现异常的代码放到try花括号中
- 当try中一旦出现异常,直接跳出try块,try中下面的代码不再执行了
2,catch(异常类型 参数名)
- catch中异常类型要和出现的异常对象类型匹配(catch小括号中的类型也可以是父类型)
3,多重catch
- 小类型在上面 大类型在下面
4,finally
- finally代码块 一定会执行的;不管有没有异常出现,也不管异常有没有被抓到都会执行
- finally就算碰到return也会执行
- 资源的释放的代码都要放到finally中
抛异常
-
当前类不处理,抛给上层调用者(谁调用我这个方法,谁就算上层调用者)进行处理
-
throw用在方法体中;throw 异常对象表示抛出异常对象
- throw一旦执行效果等价于return方法结束
-
throws方法声明处,表示此方法会抛出的异常类型
-
当抛出来的是受检异常 ,方法声明处必须加throws
-
运行时异常会被自动向上抛受检异常必须手动抛
-
在开发中异常统一抛到业务层(service)处理
常见异常类型
- NullPointerException
public static void main(String[] args) {
NullPointerException nullPointerException;
method2(null);
System.out.println("end");
}
private static void method2(String str) {
boolean y = str.equals("y");
System.out.println(y);
}
- ArithmeticException
public static void main(String[] args) {
method4(10, 0);
System.out.println("end");
}
private static void method4(int a, int b) {
System.out.println(a / b);
}
- ArrayIndexOutOfBoundsException
int[] arr = new int[3];
System.out.println(arr[3]);
System.out.println("end");