捕获和抛出异常

  • 抛出异常
  • 捕获异常
  • 异常处理五个关键字:try、catch、finally、throw、throws

实例演练

我们都知道:除数不能为0,我们在IDEA中运行一下除数为0看是否报错

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

运行结果:

在这里插入图片描述

可以看出这是一个Exception并且报错

  • 我们可以选择try——catch——finally结构避免报错
public class Outer {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        try{//try监控区域
            System.out.println(a/b);
        }catch (ArithmeticException e){//catch 捕获异常
            System.out.println("分母不能为0");
        }finally {//处理善后工作
            System.out.println("finally");
        }
        //可以不要finally
}

运行结果:

在这里插入图片描述

  1. try为监控区域

  2. catch捕获异常

  3. finally处理善后工作

  4. 可以不要finally

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

        //假设要捕获多个异常:从小到大
        try{//try监控区域
            System.out.println(a/b);
        }catch (Error e){//catch 捕获异常
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        } finally {//处理善后工作
            System.out.println("finally");
        }
}
  1. 捕获多个异常,使用多个catch

  2. 异常类型必须从小到大,否则报错

  3. 只会执行一个catch语句

  • Ctrl + Alt + T 快捷方法
package demo02;

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

}
  1. Ctrl + Alt + T ->try/catch/finally

  2. catch语句中执行的操作是打印错误的栈信息

  3. 打印错误的栈信息后还会继续执行后面的代码

  • throw和throws
public class Outer {
    public static void main(String[] args) {
        new Outer().test(1,0);
        System.out.println("Asda");
  }

        //假设这个方法中处理不了这个异常,方法上抛出异常
        public void test(int a,int b) throws ArithmeticException{
            if (b == 0) {
                throw new ArithmeticException();//主动的抛出异常,一般在方法中使用
            }
            System.out.println(a/b);
        }
}
  1. 主动的抛出异常,一般在方法中使用
  2. 假设这个方法中处理不了这个异常,方法上抛出异常
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超霸霸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值