JAVA基础之异常

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


4、自定义异常

编译异常继承Exception

运行时异常继承RuntimeException



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值