Search code examples
javafile-ioexceptionjava-8ioexception

Java compiler complaining about unreported IOException


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

Solution

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