throw关键字

@momo
1.throw
作用:thorw关键字可以在指定的方法中抛出指定的异常
使用格式:
throw newxxxException(“异常产生的原因”);

注意:
1.throw关键字必须写在方法的内部
2.throw关键字后边new的对象必须是Exception或者Exception的子类对象
3.throw关键字抛出指定的异常,我们就必须处理这个异常对象
throw关键字后边创建的是RuntimeExceptoin或者是RuntimeExceptoin的子类对象我们可以不处理,默认交给JVM处理(打印异常对象,中断程序)
throw关键字后边创建的是编译异常(写代码时候报错),我们就必须处理这个异常要么throws,要么try…catch
代码:

public class DemoThrow {
    public static void main(String[] args) {
        //int []arr =null;
        int []arr = new int [3];
        int e = getElement(arr,4);
        System.out.println(e);
    }

    public static int getElement(int []arr,int index) {
        /*
        对传递过来的数组进行合法性验证
        如果数组的值为null,就抛出空指针异常,告知传递者传递的数组值为null
         */
        if(arr==null) {
            throw new NullPointerException("传递的数组值为null");
        }
            if(index<0 ||index>arr.length-1){
                throw new ArrayIndexOutOfBoundsException("数组的索引越界");
            }

        int ele = arr[index];
        return ele;
    }

结果:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 数组的索引越界
	at day05.DemoThrow.getElement(DemoThrow.java:20)
	at day05.DemoThrow.main(DemoThrow.java:7)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值