4

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.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 3
    Apparently, Java 8 moves away from _checked_ exceptions. Almost all newly introduced exceptions are _unchecked_, and newly introduced methods use _unchecked_ exceptions, e.g. [Files.list](http://download.java.net/jdk8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-) throws an [UncheckedIOException](http://download.java.net/jdk8/docs/api/java/io/UncheckedIOException.html). – nosid Feb 11 '14 at 07:55
  • @nosid: Can’t see a general move away from checked exceptions. Only the *stream operations* will throw `UncheckedIOException` for the very same reason discussed in this question: the stream API does not allow throwing the checked `IOException`. If an `IOException` occurs before the construction of the stream it is thrown conventionally checked. – Holger Feb 11 '14 at 18:43

2 Answers2

1

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").

Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
0

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.

Boann
  • 48,794
  • 16
  • 117
  • 146