异常处理

异常处理

在这里插入图片描述

1. 抛出异常

定义 :
一个方法不处理这个异常,而是调用层次向上传递,谁调用这个方法,这个异常就由谁来处理。

throw : 将产生的异常抛出(强调的是动作),抛出的既可以是异常的引用,也可以是异常对象。(位置: 方法体内

throws : 如果一个方法可能会出现异常,但没有能力处理这种异常,可以在方法声明处用throws子句来声明抛出异常。用它修饰的方法向调用者表明该方法可能会抛出异常(可以是一种类型,也可以是多种类型,用逗号隔开)(位置: 方法名或方法名列表之后 ,在方法体之前

public class Main {
    public static void main(String[] args) {
        int a = 2;
        int b = 0;
        try {
            new Main().clac(a, b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void clac(int a, int b) throws ArithmeticException{
       // if (b == 0) throw new ArithmeticException();
        System.out.println(a / b);
    }
}

在这里插入图片描述

2. 捕获异常

直接上代码:

public static void main(String[] args) {
        int a = 2;
        int b = 0;
        System.out.println(a / b);
    }

由于0不能做分母,所以输出会报这样的异常:

Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.main(Main.java:8)

我们可以用 try catch finally 素质三连来捕获并处理异常:

public static void main(String[] args) {
        int a = 2;
        int b = 0;
        try {//监视区
            System.out.println(a / b);
        } catch (ArithmeticException e) {//捕获区(括号内为异常的种类)
            System.out.println("程序出现异常!分母不能为0");
            e.printStackTrace();//打印错误信息
        } finally {//处理善后
            System.out.println("结束");
        }
    }

输出结果:
在这里插入图片描述

注意:

  1. finally无论是否出现异常都会执行,也可以没有finally。
  2. 可以有多个catch。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值