You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加try-catch块仍报unreported exception FileNotFoundException编译错误

问题原因
  • FileNotFoundException属于Java受检异常,编译器强制要求所有受检异常必须被显式捕获,或在方法签名上通过throws声明抛出。
  • 你在fileNotFoundExTest()方法签名上声明了throws FileNotFoundException,因此调用该方法的代码块(你报错的测试代码行所在的方法)必须满足以下两个条件之一,否则会触发编译错误:
    • 调用处用try-catch捕获FileNotFoundException
    • 调用方方法的签名也添加throws FileNotFoundException声明
  • 额外说明:当前fileNotFoundExTest()的实现逻辑已经完整捕获了FileNotFoundException,运行时不会向外抛出该异常,方法签名上的throws FileNotFoundException属于多余声明。
修复方案

优先选择第一种方案:

  1. 删除fileNotFoundExTest()方法签名上多余的throws FileNotFoundException声明,修改后的代码如下:
public String fileNotFoundExTest() {
    try {
        fileNotFoundEx();
    } catch (FileNotFoundException e) {
        return "File Not Found";
    }
    return "No Error";
}
  1. 若需要保留方法的throws声明,可选择以下任意一种操作:
    • 在测试方法的签名上添加throws FileNotFoundException声明
    • 在调用fileNotFoundExTest()的位置套一层try-catch捕获异常

内容的提问来源于stack exchange,提问作者thu.vix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:24:01