Common exception handling code for extracting several methods in Java
•
Java
I have some private methods in a class with the same exception handling Their body code throws the same exception type, and the code processing is the same
private void method1() { try { //make_the_world_a_better_place } catch(IOException ioe) { // ... } } private boolean method2(String str) { try { //make_a_cheesecake } catch(IOException ioe) { // ... } }
Which is the best way to externalize common exception handling, so when I make changes to the exception handling code of one method, the changes are propagated to the other methods? The template method pattern is convenient in this case, but I don't want to go deep into the class hierarchy
Edit: there are several catch clauses, not just one in the example
Solution
Create an interface:
public interface Executor { void exec() throws Exception; }
In your class:
checkForExceptions(new Executor() { @Override public exex() throws Exception { method1(); } }); private void checkForExceptions(Executor ex) { try { ex.exec(); } catch (Exception e) [ /// handling }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码