Java 的两种异常 Checked Exception 与 Runtime Exception

Java 有两种异常: Checked Exception 与 Runtime Exception. 整理了一下两者的区别:

区别Checked ExceptionRuntime Exception
基类java.lang.Exceptionjava.lang.RuntimeException
捕获强制不强制
  1. Checked Exception 的基类是 Exception; Runtime Exception 的基类是 RuntimeException (不过 RuntimeException 的父类也是 Exception).
  2. Checked Exception 要求必须捕获. 一个方法内如果抛出了 Checked Exception, 必须要么 catch, 要么给方法声明 throws 以交给上一层去处理, 如果漏写了 catch 会直接通不过编译. Runtime Exception 就没这个要求, 不强制 catchthrows, 这样对于明显不会异常的代码段就不必处理了.

各举个例子:

  1. Runtime Exception 例子 (IndexOutOfBoundsException)

    // ArrayList 的 get 方法, 调用了 rangeCheck 方法.
    // 可以看到两个方法均没有 catch 或 声明 throws.
    public E get(int index) {
        rangeCheck(index);
    
        return elementData(index);
    }
    
    // rangeCheck 可能抛出 IndexOutOfBoundsException 这一 Runtime Exception.
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
  2. Checked Exception 例子 (FileNotFoundException)

    // FileInputStream 的构造函数, 声明了可能抛出 FileNotFoundException.
    // 同时也可能抛出 NullPointerException, 但 NullPointerException 为
    // Runtime Exception, 所以没有 throws.
    public FileInputStream(File file) throws FileNotFoundException {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        fd = new FileDescriptor();
        fd.attach(this);
        path = name;
        open(name);
    }
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值