开发者

Extracting common exception handling code of several methods in Java

开发者 https://www.devze.com 2023-02-28 02:18 出处:网络
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.

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(IOE开发者_开发技巧xception 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.


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
}


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号