publicclassNullPointerException_{publicstaticvoidmain(String[] args){String name =null;System.out.println(name.length());}}
异常:获取空字符窜的长度
(2)ArithmeticException:数学运算异常
publicclassArithmeticException_{publicstaticvoidmain(String[] args){int a =1;int b =0;System.out.println("a / b = "+ a / b);}}
异常:分母为 0
(3)ArrayIndexOutOfBoundsException:数组下标越界异常
publicclassArrayIndexOutOfBoundsException_{publicstaticvoidmain(String[] args){int[] arr ={1,2,3};for(int i =0; i <= arr.length; i++){System.out.println("arr["+ i +"] = "+ arr[i]);}}}
异常:数组只有三个元素,却访问了第四个元素
(4)ClassCastException:类型转换异常
publicclassClassCastException_{publicstaticvoidmain(String[] args){
person p_a =newA();// 向上转型A a =(A)p_a;// 向下转型// 两个不相关的类进行转换会报异常B b =(B) p_a;// A 和 B 之间无关系,不可以把指向 A 的转换为 B}}class person {}classAextends person{}classBextends person{}
异常:A 类 和 B 类 没有关系,不可以把指向 A 类 的对象转成指向 B 类 的对象
(5)NumberFormatException:数字格式不正确异常
publicclassNumberFormatException_{publicstaticvoidmain(String[] args){String name ="异常";// 将 String 转成 intint num =Integer.parseInt(name);System.out.println(num);}}
异常:无法将字符串转化为整数
三、异常处理
1. try - catch - finally
使用方法:选中可能出现异常的代码部分,使用快捷键ctrl + alt + t,在弹窗中选择需要的结构即可
publicstaticvoidmethod()throwsNullPointerException,ArrayIndexOutOfBoundsException{// NullPointerExceptionString name =null;System.out.println(name.length());// ArrayIndexOutOfBoundsExceptionint[] arr ={1,2,3};for(int i =0; i <= arr.length; i++){System.out.println("arr["+ i +"] = "+ arr[i]);}System.out.println("程序继续执行......");}
(2)抛出方法中的异常的父类
publicstaticvoidmethod()throwsRuntimeException{// NullPointerExceptionString name =null;System.out.println(name.length());// ArrayIndexOutOfBoundsExceptionint[] arr ={1,2,3};for(int i =0; i <= arr.length; i++){System.out.println("arr["+ i +"] = "+ arr[i]);}System.out.println("程序继续执行......");}
class a {publicvoidmethod()throwsRuntimeException{// NullPointerExceptionString name =null;System.out.println(name.length());}}class b extends a {@Overridepublicvoidmethod()throwsArrayIndexOutOfBoundsException{// ArrayIndexOutOfBoundsExceptionint[] arr ={1,2,3};for(int i =0; i <= arr.length; i++){System.out.println("arr["+ i +"] = "+ arr[i]);}}}
代码解析
b 类是 a 类的子类,则b 类抛出的异常必须是 a 类抛出异常类型的子类,然而 a 类抛出异常的类型NullPointerException是RuntimeException的子类,抛出的异常类型用其父类代替是没有问题的