Java基础——异常

1. 什么是异常

程序在运行过程中发生的一些意外,叫做异常,如用户输入不合法,读取文件不存在等

2. 分类

  1. 检查性异常:无法预见的,如要打开一个不存在的文件
  2. 运行时异常:在编译时被忽略,可能被避免的,如函数a,b互相调用
  3. 错误:脱离程序员控制,如栈溢出

3. 异常处理机制

  1. 抛出异常
  2. 捕获异常
  3. 异常处理关键字:try、catch、finally、throw、throws
  4. 自动捕获异常快捷键:ctrl + alt + T
// try catch finally的使用
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("后续");
    }
}
// throw 和 throws的使用
public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {
            new Demo02().test(a, b);
        } catch (ArithmeticException e) {
            System.out.println("发生了异常");
        }

    }
// 这个方法处理不了异常 向外抛出异常,由调用该方法的进行处理 在方法上使用
public void test(int a, int b) throws ArithmeticException{
    if(b == 0){
        throw new ArithmeticException(); // 在方法中使用, 用于主动抛出异常
    }
}

4. 自定义异常

继承Exception类,即可自定义异常

// 自定义异常类
public class MyException extends Exception{ // 继承Exception定义异常类
    private int detail;  // 属性
    MyException(int number){ // 构造方法
        this.detail = number;
    }
    // 转换成String
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

// 主类调用
public static void main(String[] args) {
        int a = 11;
        try {
            new Demo03().test(a);
        } catch (MyException e) {
            System.out.println("发生异常");
        }

    }
    public void test(int a) throws MyException {
        if(a > 10){
            throw new MyException(a);
        }
        System.out.println("OK");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值