问题
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