学习Java异常这一篇就够了

异常

1. 概念

  • 异常就是程序运行时可能出现的一些错误,例如数组下标越界、空指针异常等等。

2. 分类

异常的基类是Throwable类,它有2个子类:

  • Error: 不希望被程序捕获或程序无法处理的错误。例如:StackOverflowError 堆栈溢出错误等
  • Exception: 用户程序可能捕获的异常情况或者说是程序可以处理的异常。

在这里插入图片描述

异常的体系结构
在这里插入图片描述

3. 常见异常

运行时异常 (非受检异常)

异常说明
NullPointerException空指针异常
ClassCastException类型转换异常
IllegalArgumentException非法的参数异常
NubmerFormatException数字格式化异常
ArrayIndexOutOfBoundsException数组下标越界异常
StringIndexOutOfBoundsException字符串下标越界异常
IndexOutOfBoundsException下标越界异常

编译时异常 (受检异常)

异常说明
IOException输入\输出异常
FileNotFoundException文件未找到异常
SQLExceptionSQL异常
UnknownHostException未知主机异常
ClassNotFoundException类未找到异常
MalformedURLException格式错误的 URL 异常
EOFExceptionEOF异常

4. 异常处理

对于编译时异常通过throws关键字,在方法名称后面抛出可能会出现的异常

throws和throw的区别

  • throws用在方法名称后面,表示这个方法会有抛异常的行为,只是一个可能性的评估
  • throw是手动抛出异常,throw new ArithmeticException 是具体抛出异常的动作。

异常捕获

try{
        // 可能产生异常错误的语句
}catchExceptionTypeOne  e){
        // 对异常 ExceptionTypeOne 的处理语句
}catch ( ExceptionTypeTwo e) {
        // 对ExceptionTypeTwo 的处理语句
}
finally {
        // 语句块
}
  • try语句中的是可能发生异常的代码
  • catch用来捕捉异常
  • finally为异常处理的最后执行部分,无论前面的catch是否被捕捉,finally语句都会被执行。通常用来释放资源

finally面试题:

  1. 如果在try或catch块中出现return,finally还会执行吗

当Java程序执行ty块、catch块时遇到了retun语句, 并不会立马结束这个方法,而是去寻找该异常处理流程中是否包含finally语句块,如果没有finally块,方法终止,返回相应的返回值。如果有finally块, 系统立即开始执行finally块中的语句,只有当finally块执行完成后,系统才会再次回到try-catch语句中来根据return语句结束方法。

注意:如果finally块里使用了return语句,则finally块会直接执行return语句并返回,使方法结束,系统将不会跳回去执行try块、 catch块里的任何代码。

  1. finally不会被执行的情况

① 在finally 语句中发生了异常
② 在前面的代码中使用了System.exit()语句,程序提前结束
③ 程序所有的线程死亡
④ 关闭CPU

5. 自定义异常

自定义异常

/**
 * 自定义异常类
 *
 * @author yt
 */
public class BusinessException extends RuntimeException {

    private final int code;

    private final String description;

    public BusinessException(String message, int code, String description) {
        super(message);
        this.code = code;
        this.description = description;
    }

    public BusinessException(ErrorCode errorCode) {
        super(errorCode.getMessage());
        this.code = errorCode.getCode();
        this.description = errorCode.getDescription();
    }

    public BusinessException(ErrorCode errorCode, String description) {
        super(errorCode.getMessage());
        this.code = errorCode.getCode();
        this.description = description;
    }

    public int getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值