Java编译器抱怨未报告的IOException
我正在尝试编写一个列出目录中所有非隐藏文件的方法。 但是,当我添加条件!Files.isHidden(filePath)
我的代码将无法编译,并且编译器返回以下错误:
java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.IOException; must be caught or declared to be thrown
我试图捕获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(); }
传递给Iterable#forEach
的lambda表达式不允许抛出exception,因此您需要在那里处理它:
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 } });
isHiddenFile()
抛出一个IOException,而你却没有捕获它。 实际上, forEach()
将Consumer作为参数,而Consumer.accept()
不能抛出任何已检查的exception。 所以你需要通过传递给forEach()
的lambda表达式来捕获exception:
Files.walk(Paths.get(root)).forEach(filePath -> { try { if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) { System.out.println(filePath); } } catch (IOException e) { // do something here } });