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

  • A+
Category:Languages

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

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: