Can a terminal operation (e.g. forEach) recheck exceptions?

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 against the use of a method reference:

void deepDelete(Path root) throws IOException {
    Files.walk(root)
            .filter(p -> !Files.isDirectory(p))
            .forEach(Files::delete); //does not compile
}

Unfortunately, this code does not compile.

Is there a way to apply an action that throws checked exceptions in a terminal operation and simply "reconstructs" any exceptions?

I understand that I can write a wrapper that converts a checked exception to an exception, but I prefer sticking to methods in the JDK if possible.

+4
source share
2 answers

: . techempower java8, (. " " ).

+1

:

@SuppressWarnings("unchecked")
static <T extends Throwable> RuntimeException sneakyThrow(Throwable t) throws T {
    throw (T)t;
}

:

try {
    Files.delete(p);
} catch (IOException e) {
    throw sneakyThrow(e);
}

raw IOException , . , , .

0

Source: https://habr.com/ru/post/1526261/


All Articles