异常

异常

Java中的异常体系:
Throwable: 异常和错误的父类
在这里插入图片描述

JVM处理异常的方式

1.打印错误信息

2.终止程序

常规处理异常的方式

1.throws处理异常 (不负责)

2.try…catch处理异常 (负责任)

throw关键字

throw的作用: 创建/产生/制造异常

格式

throw new 异常类名();

代码实例

public static void main(String[] args) throws Exception {

    throw new Exception("搞事");//创建一个异常
    
}

throws处理异常

处理异常的一种方式

声明异常, 将异常抛给别人处理

格式

修饰符 返回值类型 方法名(参数列表) throws 异常的类名1, 异常的类名2 {

}

throw于throws的区别

throw:
作用: 创建/制造异常
格式: throw new 异常类名(); throw后面跟的是异常的对象
数量: throw后面只能跟一个异常对象

throws:
作用: 处理异常的一种方式,声明异常,让别人处理异常
格式: throws后面跟的是异常的类名
数量: throws后面可以跟多个异常的类名

代码实例

public static void main(String[] args) {//将异常抛给jvm  打印错误信息,中止程序
    test1();//调用方法
}

private static void test1() throws ArithmeticException{ //将异常抛给main方法处理,还是会报异常

    int a = 1;
    int b = 0;

    int c = a/b;

    System.out.println(c);

}

try…catch捕获异常

格式

try…catch处理异常的好处:程序会接着往下走.不会崩溃

try {
可能出现问题的代码;

​ } catch (异常类名 变量名) {

​ 处理异常的代码;
​ }

若代码没有问题,则不执行catch方法体中的代码

无论有没有执行catch方法体中的代码,都会执行之后的代码

代码实例

public static void main(String[] args) {

        int a = 10;
        int b = 0;

        try {

            int c = a / b;
        } catch (ArithmeticException e) {
//            System.out.println("除数不能为0");
            a = 10;
            b = 2;
            System.out.println(a/b);
            
        }
        System.out.println("走我了吗?");//捕获异常后,后面的编码还能够运行

    }

finally关键字

finally关键字修饰的代码块,一定会被执行

代码示例

public static void main(String[] args) {
int a = 10;
int b = 0;

    try {
        int c = a / b;
        System.out.println(c);
    } catch (ArithmeticException e) {
        System.out.println("处理除数为0的异常");
        return; // 结束方法
    } finally {
        System.out.println("我是一定会被执行的代码");
        System.out.println("我是一定会被执行的代码");
    }

    System.out.println("走我了吗?");
}
   } finally {
        System.out.println("我是一定会被执行的代码");
        System.out.println("我是一定会被执行的代码");
    }

    System.out.println("走我了吗?");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值