lefloh
lefloh

Reputation: 10961

Catch Exception from Method Reference

I’m trying to pass a method reference which throws a checked Exception:

Files.list((Paths.get("/some/path"))).map(Files::readAllLines);

How can I handle this exception (without wrapping the method reference in a method which handles the exeption).

Upvotes: 2

Views: 1177

Answers (1)

Rogue
Rogue

Reputation: 11483

If you're attempting to catch an exception for a specific value in the .map I wouldn't recommend a method reference, instead use a lambda:

Files.list((Paths.get("/some/path"))).map((someVal) -> {

    try {
        //do work with 'someVal'
    } catch (YourException ex) {
        //handle error
    }

});

If you want to rethrow the exception after, you can do so manually with a reference to the error through a box:

//using the exception itself
final Box<YourException> e = new Box<>();
Files.list((Paths.get("/some/path"))).map((someVal) -> {

    try {
        //do work with 'someVal'
    } catch (YourException ex) {
        //handle error
        e.setVar(ex);
    }

});
if (e.getVar() != null) {
    throw e.getVar();
}

class Box<T> {
    private T var;
    public void setVar(T var) { this.var = var; }
    public T getVar() { return this.var; }
}

Upvotes: 8

Related Questions