Java复习(4)-异常处理

1.try-catch-finally

public class ThrowableTry {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int a,b;
        int[] c = new int[3];
        try{
            a = 0;
            c[3] = 3;
            b = 5/a;//先碰到上面的异常,这个异常就不运行了。

            System.out.println("需要检验的程序");


        }
        catch(ArithmeticException e){
            System.out.println("发生ArithmeticException  "+e);
        }
        catch(Exception e){
            System.out.println("发生ArrayIndexOutOfBoundsExceptionn   "+e);
        }
        finally{
            System.out.println("over");//finally是一定会运行的
        }
    }

}

运行结果:

发生ArrayIndexOutOfBoundsExceptionn   java.lang.ArrayIndexOutOfBoundsException: 3
over

2.throw 和throws

public class Throws {
    public static void main(String[] args){
        //throwsTest();
        throwTest();
    }

    //测试中发现不写throws以及后面内容也是可以的,怎么回事?
    public void methodName(int x) throws ArrayIndexOutOfBoundsException,ArithmeticException{
        System.out.println(x);
        if(x == 0){
            System.out.println("没有异常");
            return;
        }
        else if(x == 1){
            int[] a = new int[3];
            a[3] = 5;
        }
        else if(x == 2){
            int i = 0;
            int j = 5/i;
        }
    }

    public static void throwsTest(){
        Throws a = new Throws();
        try {
            a.methodName(0);

        }
        catch(Exception e){
            System.out.println("异常:"+e);

        }
        try{
            a.methodName(1);

        }
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println("异常:"+e);
        }
        try{
            a.methodName(2);

        }
        catch(ArithmeticException e){
            System.out.println("异常:"+e);
        }
    }



    public void methodName(){
        try{
            throw new ArrayIndexOutOfBoundsException();//这里的throw 必须加
        }
        catch(ArrayIndexOutOfBoundsException aoe){
            throw aoe;
        }
    }

    public static void throwTest(){
        Throws a = new Throws();
        try{
            a.methodName();
        }
        catch(ArrayIndexOutOfBoundsException aoe){
            System.out.println("异常:"+aoe);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值