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

Viewed 254

New to java 8, I would like to optimise my code bellow:

public Response create() {
    try{
        ...
    } catch (Exception e) {
        codeA;
    } finally {
        codeB;
    }
}

public Response update() {
    try{
        ...
    } catch (Exception e) {
        codeA;
    } finally {
        codeB;
    }
}

I have a lot of methods using this same way to catch exceptions and do the same finally, is that possible to replace the bellow common code by a method in java 8? So that I could optimise all my methods who use this common code.

} catch (Exception e) {
    codeA;
} finally {
    codeB;
}
3 Answers

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());
}

This could be a generic solution.

//here describe supplier which can throw exceptions

@FunctionalInterface
public interface ThrowingSupplier<T> {
    T get() throws Exception;
}

// The wrapper
private <T> T callMethod(ThrowingSupplier<T> supplier) {
    try {
        return supplier.get();
    } catch (Exception e) {
        //code A
    }finally {
        // code B
    }
}
Related