以下不断报告相同的错误.
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)
有解决方案吗
嗯,你有三个选择:
findMatches以便它不会声明它抛出FileNotFoundException(此刻肯定不会抛出它)FileNotFoundException调用代码findMatches抛出FileNotFoundException我们无法从您提供的极少量信息中分辨哪一个最合适.
您还需要阅读Java教程的Exceptions部分,或任何优秀Java书籍/教程的异常覆盖.了解为什么会出现此错误以及上述更改为何会解决此问题非常重要.
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |