jilt3d
jilt3d

Reputation: 4044

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.

Upvotes: 8

Views: 5304

Answers (4)

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

Create an interface:

public interface Executor {

  void exec() throws Exception;

}

in your class:

checkForExceptions(new Executor() {

  @Override
  public exec() throws Exception {

    method1();

  }

});

private void checkForExceptions(Executor ex) {
  try {
    ex.exec();
  } catch (Exception e) {
    /// handling
  }
}

Upvotes: 6

user6550325
user6550325

Reputation: 1

I was thinking for a try-catch-handling at one place and the method's logic between them, but I guess the world then would be too perfect. Actually I have several catch clauses in the methods.

Upvotes: -1

Peter Lawrey
Peter Lawrey

Reputation: 533750

You can create a handleException(IOException ioe) method which they both call.

Upvotes: 2

duffymo
duffymo

Reputation: 308988

Your instinct is good - DRY is a good thing. But don't do this. Your code will be harder to read.

Make sure your catch blocks are really handling the exception and not just swallowing it. If your class isn't providing remediation, I'd say it'd be better to throw it and let clients figure out what to do.

Upvotes: 2

Related Questions