09-异常

异常

Exception

异常指程序中出现的不期而至的各种状况:文件找不到、网络连接失败等

分类

  • 检查性异常:无法预见,如文件不存在

  • 运行时异常:程序没有错误,运行出错

  • 错误

异常体系机构

在这里插入图片描述

java.lang.Throwable作为所有异常的超类:

  • 错误Error
  • 异常Exception

Error和Exception区别

  • Error是致命错误,是程序无法控制和处理的,当出现错误时,Java 虚拟机(JVM)会选择终止进程
  • Exception 是可以被程序处理的,并且再程序中应该尽可能地去处理这些异常

异常处理机制

int a = 1;
int b = 0;

// 假设要捕获多个异常,从小到大!
//ctrl + alt + T
try {   //try监控区域
    if (b == 0){
        throw new ArithmticException();        //主动抛出异常
    }
    System.out.println(a/b);
}catch (Error e){     //捕获错误
    System.out.println("error");
}catch (Exception e){   //捕获异常
    System.out.println("exception");
}catch (Throwable t){   //捕获Throwable
    System.out.println("throwable");
} finally {      //处理后续工作
    System.out.println("finally");
}

//finally 可以不用
public class Demo02 {
    public static void main(String[] args) {
//        new Demo02().test(1, 0);
        try {
            new Demo02().test(1, 0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }

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

关键字:try、catch、finally、throw、throws

自定义异常

  1. 自定义异常类
  2. 在方法中通过throw关键字抛出异常对象
  3. 如果在当前抛出异常的处理方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出的异常,继续进行下一步操作
  4. 在出现异常方法的调用者中捕获并处理异常
package exception;

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

    public MyException(int a){
        this.detail = a;
    }

    //toString: 异常的打印信息

    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
package exception;

public class Demo03 {

    //可能会存在异常的方法
    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(11);
        }catch (MyException e){
            System.out.println("MyException:" + e);
        }
    }
}
  • 处理运行时异常时,采用逻辑去合理规避同时辅助 try-catch处理
  • 在多重catch块后,可以加一个catch(Exception)来处理可能会被遗漏的异常
  • 对于不确定的代码,也可以加上try-catch
  • 尽量处理异常,加上代码处理块
  • 添加finally语句释放占用资源,IO~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值