How to regroup catch finally into one method in java 8?

Depends what you do in the .... You could do something like this:

private Response method(Supplier<Response> supplier) {
    try{
        return supplier.get();
    } catch (Exception e) {
        codeA;
    } finally {
        codeB;
    }
}

and invoke like:

public Response create() { return method(() -> { ... for create }); }
public Response update() { return method(() -> { ... for update }); }

You could wrap your payload and put it to the separate method. One thing; what do you expect to return on exception catch. This time this is null, but probably you could provide default value.

public static <T> T execute(Supplier<T> payload) {
    try {
        return payload.get();
    } catch(Exception e) {
        // code A
        return null;
    } finally {
        // code B
    }
}

Client code could look like this:

public Response create() {
    return execute(() -> new CreateResponse());
}

public Response update() {
    return execute(() -> new UpdateResponse());
}

Tags:

Java

Java 8