Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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;
}
like image 918
henriwang Avatar asked Jan 04 '19 14:01

henriwang


2 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 }); }
like image 137
Andy Turner Avatar answered Oct 05 '22 22:10

Andy Turner


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());
}
like image 26
oleg.cherednik Avatar answered Oct 06 '22 00:10

oleg.cherednik