添加try-catch块仍报unreported exception FileNotFoundException编译错误
问题原因
FileNotFoundException属于Java受检异常,编译器强制要求所有受检异常必须被显式捕获,或在方法签名上通过throws声明抛出。- 你在
fileNotFoundExTest()方法签名上声明了throws FileNotFoundException,因此调用该方法的代码块(你报错的测试代码行所在的方法)必须满足以下两个条件之一,否则会触发编译错误:- 调用处用try-catch捕获
FileNotFoundException - 调用方方法的签名也添加
throws FileNotFoundException声明
- 调用处用try-catch捕获
- 额外说明:当前
fileNotFoundExTest()的实现逻辑已经完整捕获了FileNotFoundException,运行时不会向外抛出该异常,方法签名上的throws FileNotFoundException属于多余声明。
修复方案
优先选择第一种方案:
- 删除
fileNotFoundExTest()方法签名上多余的throws FileNotFoundException声明,修改后的代码如下:
public String fileNotFoundExTest() { try { fileNotFoundEx(); } catch (FileNotFoundException e) { return "File Not Found"; } return "No Error"; }
- 若需要保留方法的
throws声明,可选择以下任意一种操作:- 在测试方法的签名上添加
throws FileNotFoundException声明 - 在调用
fileNotFoundExTest()的位置套一层try-catch捕获异常
- 在测试方法的签名上添加
内容的提问来源于stack exchange,提问作者thu.vix
相关产品推荐
相关产品推荐

