Java学习笔记63. 由开发者抛出异常的两种方法 -- throws 和 throw

前面总结了由系统抛出异常的情形,基本上,就算不写捕捉异常的语句,系统也会把异常抛出来并中止程序的运行。

但是有时候,需要开发者自己设计抛出异常的方式,这样就用到了throw和throws关键字。

throw是在方法中抛出异常,而throws是在方法声明的时候抛出异常

下面是一个在程序中使用throw关键字抛出异常的例子:

public class testThrow{
    static int add(int a,int b){
        if(b==0)        //如果除数为0,就抛出一个异常
            throw new ArithmeticException("There is an error!");    //先new一个异常对象,然后由throw关键字抛出,并附带一个字符串参数
        else
            return a/b;
    }
    public static void main(String[] args){
        int a = 1, b=0;
        add(a,b);    //调用静态方法
    }
}

如果在方法中没有定义捕捉和处理异常的语句,也可以在方法声明的时候使用throws关键字抛出异常,给方法的调用处来处理,比如:

public class testThrows{

     void addArray(int[] a)throws ArrayIndexOutOfBoundsException{    //抛出数组下标越界异常
        int x1 = a[5];    //下标越界
    }
    public static void main(String[] args){
        int[] b = {1,0,3};
        try{    //准备检查异常
            new testThrows().addArray(b);
        }catch(ArithmeticException e){    //捕捉算数异常
            System.out.println("There is an ArithmeticException.");
        }catch(ArrayIndexOutOfBoundsException e2){    //捕捉数组下标越界异常
            System.out.println("ArithmeticException");
        }
    }
}
编译执行


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值