Java compiler complaining about unreported IOException

这一生的挚爱 提交于 2019-12-21 20:44:12

问题


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

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

回答1:


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



回答2:


isHiddenFile() throws an IOException, and you're not catching it. Indeed, forEach() takes a Consumer as argument, and Consumer.accept() can't throw any checked exception. So you need to catch the exception inside by the lambda expression passed to forEach():

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


来源:https://stackoverflow.com/questions/32034591/java-compiler-complaining-about-unreported-ioexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!