1、异常的继承体系
超类,所有异常的父类Throwable
两大子类Exception(异常)和Error(错误)
Exception(异常)下有RuntimeException(运行时异常)
2、异常的使用
(1)抛出异常
throw new 异常类名(参数);
例子:
class ArrayTools{
//通过给定的数组,返回给定的索引对应的元素值。
public static int getElement(int[] arr,int index){
/*
若程序出了异常,JVM它会打包异常对象并抛出。但是它所提供的信息不够给力。想要更清晰,需要自己抛出异常信息。
下面判断条件如果满足,当执行完throw抛出异常对象后,方法已经无法继续运算。这时就会结束当前方法的执行,并将异常告知给调用者。这时就需要通过异常来解决。
*/
if(arr==null){
throw new NullPointerException("arr指向的数组不存在");
}
if(index<0 || index>=arr.length){
throw new ArrayIndexOutOfBoundsException("错误的角标,"+index+"索引在数组中不存在");
}
int element = arr[index];
return element;
}
}
(2)申明异常
例子:
public static int getElement(int[] arr,int index) throws NullPointerException, ArrayIndexOutOfBoundsException {
if(arr==null){
throw new NullPointerException("arr指向的数组不存在");
}
if(index<0 || index>=arr.length){
throw new ArrayIndexOutOfBoundsException("错误的角标,"+index+"索引在数组中不存在");
}
int element = arr[index];
return element;
}
(3)捕获异常(try…catch…finally)
例子:
class ExceptionDemo{
public static void main(String[] args){ //throws ArrayIndexOutOfBoundsException
try{
int[] arr = new int[3];
System.out.println( arr[5] );// 会抛出ArrayIndexOutOfBoundsException
当产生异常时,必须有处理方式。要么捕获,要么声明。
}
catch (ArrayIndexOutOfBoundsException e) { //括号中需要定义什么呢?try中抛出的是什么异常,在括号中就定义什么异常类型。
System.out.println("异常发生了");
} finally {
arr = null; //把数组指向null,通过垃圾回收器,进行内存垃圾的清除
}
System.out.println("程序运行结果");
}
}
3、异常中常用方法:getMessage(返回详细消息字符串)、prinkStrackTrace、toString
编译异常继承Exception
运行时异常继承RuntimeException