java的异常处理

java的异常处理

try catch finally

package Test;

public class Demo01 {



    public static void main(String[] args) {

        int a = 1;
        int b = 0;
        //ctrl + alt + t
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            System.out.println("Exception");
            //e.printStackTrace();//打印错误的栈信息
        } catch (Error e){
            System.out.println("Error");
        }catch (Throwable t){//catch(捕获异常的类型 异常名eg:e,t)
                            //注意异常范围从小到大 Throwable为最大的范围放在最后面
            //如果Throwable放在前面直接报错,直接将大范围的异常捕获后面的范围不执行
            System.out.println("Throwable");
        }
        finally {
            System.out.println("是否抛出异常都要执行,用于善后处理工作");
        }

    }
}

throw 和 throws

package Test;

public class Demo01 {



    public static void main(String[] args) {
        try {
            new Demo01().test(1,0);
        } catch (ArithmeticException e) {//用于解决test方法解决不了抛出的异常
            e.printStackTrace();
            System.out.println("接收解决方法上的异常");
        } finally {
        }

    }
    //假设这个方法解决不了这个异常,可以在方法上抛出去throws
    public void test(int a ,int b) throws ArithmeticException{
        if(b==0){
            throw new ArithmeticException();//主动抛出一个异常,注意使用的throw不是throws
                //throw一般用在方法中
        }
        System.out.println(a/b);
    }
}

自定义异常

package Test;
//自定义异常
public class MyException extends Exception{
    //定义一个值
    public int detail;
        //进行参数构造
    public MyException( int detail) {

        this.detail = detail;
    }
    //toString 打印异常信息
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

package Test;

public class Test {
    public void test(int b){
        if(b>10){
            try {//第一种方式在方法内捕获
                throw new MyException(b);
            } catch (MyException e) {
                System.out.println("异常超过10");
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new Test().test(12);
    }
}

package Test;

public class Test {//第二种方式抛出异常,让调用这个方法的时候来捕获,外面捕获
    public static void test(int b) throws MyException {
        if(b>10){
            System.out.println("异常");
            throw new MyException(b);
        }
        System.out.println("ok");
    }

    public static void main(String[] args) {
        try {
            test(12);
        } catch (MyException e) {
            e.printStackTrace();
        }


    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值