FileNotFoundException的方法

-2 java filenotfoundexception

以下不断报告相同的错误.

public static ArrayList<File> findMatches(File directory, String pattern) throws FileNotFoundException {
60         ArrayList<File> container = new ArrayList<File>();
61 
62         return container;
63     }
Run Code Online (Sandbox Code Playgroud)

我用以下方式初始化它

ArrayList<File> matched = findMatches(new File("hw9"), "FileFinder.java");
Run Code Online (Sandbox Code Playgroud)

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

有解决方案吗

编辑

终于找到了怎么做!

public static ArrayList<File> findMatches(File directory, String pattern) throws FileNotFoundException {
    ArrayList<File> container = new ArrayList<File>();

    try {
        if (!directory.exists() && !directory.canRead() && !directory.isDirectory()) {
            throw new FileNotFoundException();
        }
        File[] fileStack = directory.listFiles();
        for (int i = 0; i < fileStack.length; i++) {
            if (patternMatches(pattern, fileStack[i].getName())) {
                container.add(fileStack[i]);
            }
        }
    } catch (NullPointerException e) {
        throw new FileNotFoundException();
    }
    return container;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

有解决方案吗

嗯,你有三个选择:

  • 改变,findMatches以便它不会声明它抛出FileNotFoundException(此刻肯定不会抛出它)
  • 抓住FileNotFoundException调用代码
  • 声明调用方法findMatches抛出FileNotFoundException

我们无法从您提供的极少量信息中分辨哪一个最合适.

您还需要阅读Java教程Exceptions部分,或任何优秀Java书籍/教程的异常覆盖.了解为什么会出现此错误以及上述更改为何会解决此问题非常重要.