【问题标题】:unreported exception despite of try-catch block尽管有 try-catch 块,但未报告的异常
【发布时间】:2021-11-12 15:23:18
【问题描述】:

我正在编写一个程序来练习抛出异常,并在其中一个测试中得到编译错误:

MyTest.java:29:错误:未报告的异常 FileNotFoundException;必须被抓住或宣布被抛出:

Assert.assertEquals("找不到文件", task2.fileNotFoundExTest());

^

public void fileNotFoundEx() throws FileNotFoundException {
        File fileName = new File("foo.txt");
        BufferedReader rd = new BufferedReader(new FileReader(fileName));
    }

public String fileNotFoundExTest() throws FileNotFoundException {
        try {
            fileNotFoundEx();
        } catch (FileNotFoundException e) {
            return "File Not Found";
        }
        return "No Error";
    }

我不知道为什么会出现这个错误,因为我已经将导致异常的方法放在了 try-catch 块中,并为这两个方法添加了签名“throws FileNotFoundException”。谁能解释一下?

【问题讨论】:

    标签: java exception


    【解决方案1】:

    您已声明该方法会引发异常 - 它不会:

    public String fileNotFoundExTest() throws FileNotFoundException {
    

    只需更改为:

    public String fileNotFoundExTest() {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      相关资源
      最近更新 更多