use*_*553 3 java file-io exception-handling ioexception java-8
我正在尝试编写一个列出目录中所有非隐藏文件的方法.但是,当我添加条件时,!Files.isHidden(filePath)我的代码将无法编译,并且编译器返回以下错误:
java.lang.RuntimeException: Uncompilable source code - unreported exception
java.io.IOException; must be caught or declared to be thrown
Run Code Online (Sandbox Code Playgroud)
我试图赶上IOException,但编译器仍然拒绝编译我的代码.有什么明显的东西让我失踪吗?代码如下.
try {
Files.walk(Paths.get(root)).forEach(filePath -> {
if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) {
System.out.println(filePath);
} });
} catch(IOException ex) {
ex.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
传递给lambda的表达式Iterable#forEach不允许抛出异常,所以你需要在那里处理它:
Files.walk(Paths.get(root)).forEach(filePath -> {
try {
if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) {
System.out.println(filePath);
}
} catch (IOException e) {
e.printStackTrace(); // Or something more intelligent
}
});
Run Code Online (Sandbox Code Playgroud)