Java编译器抱怨未报告的IOException [英] Java compiler complaining about unreported IOException

查看:210
本文介绍了Java编译器抱怨未报告的IOException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个列出目录中所有非隐藏文件的方法。但是,当我添加条件!Files.isHidden(filePath)我的代码将不会编译,编译器返回以下错误:

I'm trying to write a method that lists all non-hidden files in a directory. However, when I add the condition !Files.isHidden(filePath) my code won't compile, and the compiler returns the following error:

java.lang.RuntimeException: Uncompilable source code - unreported exception 
java.io.IOException; must be caught or declared to be thrown

我试图抓住 IOException ,但编译器仍然拒绝编译我的代码。有没有什么明显的,我失踪了?代码列在下面。

I tried to catch the IOException, but the compiler still refuses to compile my code. Is there something glaringly obvious that I'm missing? Code is listed below.

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(); 
}


推荐答案

a href =http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer- =nofollow> Iterable#forEach 不允许抛出异常,所以你需要处理它:

The lambda expression passed to Iterable#forEach isn't allowed to throw an exception, so you need to handle it there:

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
    }
});

这篇关于Java编译器抱怨未报告的IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆