java异常

自定义异常

public class MyException extends Exception {

    private int errCode;

    public MyException() {
    }

    public MyException(String message, int errCode) {
        super(message);
        this.errCode = errCode;
    }

    public int getErrCode() {
        return errCode;
    }
}

异常测试

public class ExceptionTest {

    public static void main(String[] args) {
        ExceptionTest exceptionTest = new ExceptionTest();
        for (int i = 0; i < 3; i++) {
            System.out.println("第" + i + "次循环");
            exceptionTest.test1(i);
            System.out.println("------------------");
        }
    }

    // 抓住异常
    public int test1(int t) {
        int i = 0;
        try {
            test2(t);
            i = 1;
            System.out.println("try:"+i);
            return i;
        } catch (MyException e) {
            System.out.println("出现异常");
            System.out.println("错误代码:"+e.getErrCode()+",错误内容:"+e.getMessage());
            i = 2;
            System.out.println("catch:"+i);
            return i;
        } finally {
            i = 3;
            System.out.println("finally:"+i);
            return i;
        }
    }

    // 抛出异常
    public void test2(int t) throws Exception{

        try {
            double result = 10 / t;
        } catch (Exception e) {
            throw new MyException("分母为0", 100);
        }
    }
    
}

输出

第0次循环
出现异常
错误代码:100,错误内容:分母为0
catch:2
finally:3
------------------
第1次循环
try:1
finally:3
------------------
第2次循环
try:1
finally:3
------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值