【问题标题】:Java compiler complaining about unreported IOExceptionJava 编译器抱怨未报告的 IOException
【发布时间】:2015-08-16 11:32:07
【问题描述】:

我正在尝试编写一个列出目录中所有非隐藏文件的方法。但是,当我添加条件!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(); 
}

【问题讨论】:

  • @the compiler 仍然拒绝编译我的代码" - 是同样的错误还是不同的错误?
  • @mikej 出现同样的错误
  • 您可以尝试这里列出的方法:stackoverflow.com/questions/31270759/…

标签: java file-io exception-handling java-8 ioexception


【解决方案1】:

传递给Iterable#forEach的lambda表达式不允许抛出异常,所以你需要在那里处理:

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

【讨论】:

  • 请注意,通常允许 lambda 表达式抛出异常。此处使用的特定功能接口是不允许的。
  • @TagirValeev 我认为在我的回答中使用“The”而不是“A”传达了这个概念,但在重新阅读它时,我同意这一点不够清楚。我编辑了文本以澄清这一点。感谢您的反馈!
  • 嗯,这可能是我的问题。在我的母语中没有冠词,所以有时我只是没有注意到它们在句子中添加的额外含义。尽管如此,澄清是好的。
【解决方案2】:

isHiddenFile() 抛出一个 IOException,而你没有捕捉到它。事实上,forEach() 将 Consumer 作为参数,Consumer.accept() 不能抛出任何已检查的异常。所以你需要通过传递给forEach()的lambda表达式捕获异常inside

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

【讨论】:

    猜你喜欢
    • 2011-01-08
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多