异常...

12 篇文章 0 订阅
9 篇文章 0 订阅

异常

Erro和Exception

image-20210818060327222

image-20210818060546753

image-20210818060616370

image-20210818060735202

捕获和抛出异常

image-20210818060810183

package exception;

public class Demo {
    public static void main(String[] args) {
        //假设要捕获多个异常: 从小到大
        int a = 1;
        int b = 0;

        try {
            if (b == 0) {
                throw new ArithmeticException(); //主动抛出异常
            }
            System.out.println(a / b);


            //监控区域
            System.out.println(a / b);
        } catch (ArithmeticException e) { //捕获异常类型
            System.out.println("程序出现错误");
        } finally {//善后工作
            System.out.println("finally");
        }


    }
}
package exception;

public class Demo2 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace(); //打印错误的栈信息
        } finally {
            System.out.println("finally");

        }
    }


}
package exception;

public class Demo3 {
    public static void main(String[] args) {

        try {
            new Demo3().test(1, 0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }

    }


    public void test(int a, int b) throws ArithmeticException {
        if (b == 0) {
            throw new ArithmeticException(); //主动抛出异常,一般在方法中使用
        }

    }


}

自定义异常

image-20210818061102127

package exception;

//自定义的异常类
public class MyException extends Exception {
    //传递数字>10
    private int delail;

    public MyException(int a) {
        this.delail = a;
    }
    //toString

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

}
package exception;

public class test {
    static void test(int a) throws MyException {
        System.out.println("传递的数值:" + a);
        if (a > 10) {
            throw new MyException(a);//抛出
        }

        System.out.println("ok");
    }

    public static void main(String[] args) {
        try {
            test(50);
        } catch (MyException e) {
            System.out.println("MyException==>" + e);
        }

    }


}
try {
            test(50);
        } catch (MyException e) {
            System.out.println("MyException==>" + e);
        }

    }


}

源代码

GitHub:https://github.com/YixinWen/java.git (javaSE 分支)
Gitee(码云):https://gitee.com/wenyixin666/java.git (javaSE 分支)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值