Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting common exception handling code of several methods in Java

I have some private method in a class which has equal exception handling. Their body code raises equal exception types and the code handling 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 the common exception handling, so when I make a change in the exception handling code of one of the methods the change will propagate to other methods? Template Method pattern would be handy in this situation, but I don't want go deep into the class hierarchy.

EDIT: There are several catch clauses, not only one like in the example.

like image 388
jilt3d Avatar asked Apr 20 '11 09:04

jilt3d


1 Answers

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
}
like image 151
Vladimir Ivanov Avatar answered Sep 29 '22 13:09

Vladimir Ivanov