As far as I can tell: no. I use this techempower article as my java8 guide, and it's pretty explicit (see the section headed "Exception transparency").
Can a terminal operation (e.g. forEach) rethrow checked exceptions?
-
09-10-2022 - |
Question
I have a method that deletes some files:
void deepDelete(Path root) {
Files.walk(root)
.filter(p -> !Files.isDirectory(p))
.forEach(p -> { try { Files.delete(p); }
catch (IOException e) { /* LOG */ }
});
}
The try/catch block reduces the readability of the operation, especially vs. using a method reference:
void deepDelete(Path root) throws IOException {
Files.walk(root)
.filter(p -> !Files.isDirectory(p))
.forEach(Files::delete); //does not compile
}
Unfortunately that code does not compile.
Is there a way to apply an action that throws checked exceptions in a terminal operation and simply "rethrow" any exceptions?
I understand that I could write a wrapper that transforms the checked exception into an unchecked exception but I would rather stick to methods in the JDK if possible.
Solution
OTHER TIPS
If you declare this method:
@SuppressWarnings("unchecked")
static <T extends Throwable> RuntimeException sneakyThrow(Throwable t) throws T {
throw (T)t;
}
Then you can do:
try {
Files.delete(p);
} catch (IOException e) {
throw sneakyThrow(e);
}
This bypasses the checked exception rules and throws the raw IOException
without wrapping, although you still have to catch it & rethrow. I'm not saying this is a good idea, but it's an idea.