Java异常捕捉不抛出_为什么捕获检查的异常允许不抛出异常的代码?

在Java中,抛出 checked 异常(Exception或其子类型 - IOException,InterruptedException等)的方法必须声明 throws 语句:

public abstract int read() throws IOException;

不声明 throws 语句 can't 抛出已检查异常的方法 .

public int read() { // does not compile

throw new IOException();

}

// Error: unreported exception java.io.IOException; must be caught or declared to be thrown

但是在安全方法中捕获已检查的异常在java中仍然是合法的:

public void safeMethod() { System.out.println("I'm safe"); }

public void test() { // method guarantees not to throw checked exceptions

try {

safeMethod();

} catch (Exception e) { // catching checked exception java.lang.Exception

throw e; // so I can throw... a checked Exception?

}

}

实际上,没有 . 这有点好笑:编译器知道 e 不是一个经过检查的异常并允许重新抛出它 . 事情甚至有点荒谬,这段代码不编译:

public void test() { // guarantees not to throw checked exceptions

try {

safeMethod();

} catch (Exception e) {

throw (Exception) e; // seriously?

}

}

// Error: unreported exception java.lang.Exception; must be caught or declared to be thrown

第一个片段是一个问题的动机 .

编译器知道检查的异常不能被抛出一个安全的方法 - 所以也许它应该只允许捕获未经检查的异常?

回到 main question - 有没有理由以这种方式实现捕获检查的异常?这只是设计中的缺陷还是我遗漏了一些重要因素 - 可能是后向不兼容?如果在这种情况下只允许 RuntimeException 被捕获,可能会出现什么问题?非常感谢例子 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值