2

Is it an anti-pattern to handle exception in a separate method?

Say i have a method that does some low-level IO and may throw an IOException, and i have a method foo() that calls the low-level IO method several times. Does it make sense to do the exception-handling in a 3rd method like this:

 public void foo()  throws MyCheckedException {
     // some stuff
     goDoSomeIO(path1)
    // some other stuff
     goDoSomeIO(path2)
    // some more stuff
     goDoSomeIO(path3)

  }

 private String goDoSomeIO(String filePath) throws MyCheckedException {
     try {
         doSomeIO(filePath);
     } catch (IOException ioe) {
         LOG.error("Io failed at: " + filePath);
         throw new MyCheckedException("Process failed because io failed", ioe)
     }
  }

 private String doSomeIO(String filepath) throws IOException {
        //io stuff
  }

I find this is more readable than it would be if the doSomeIO method did its own exception handling, or if the exception handling happend in foo.

Ivana
  • 643
  • 10
  • 27

2 Answers2

2

The general rule of catching [checked] exception is to do it when you can recover from the 'exceptional' situation that occurred. If you can't recover from the exception here, let it bubble up to a level at which it can be recovered. For example, notify the user the selected file is unreadable and allow the user to select a file again. Or to send a 404 'page' to the requester when the actually requested page doesn't exist.

Effective Java, Item 58

A commonly used exception to this rule is to catch, do some trivial non-recovering work (like logging) and rethrow the exception (possibly wrapped). I see nothing wrong with your approach.

It's actually a pro-pattern to add extra details to the exception and rethrowing it.

Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50
2

I frequently see code that handles exceptions of lower level methods at a higher level, regardless if the lower level is just one method or several.

That's quite common and is due to segregated concerns: Low level stuff takes care of pushing files around, high level stuff catches exceptions to determine if a complex operation worked or not. I don't think there's anything wrong with putting the handling of IO and handling of IO in different methods. (I'd try to give them some name, that explains the purpose however. I'm not a fan of goDoWhatever & doWhatever)

froh42
  • 5,190
  • 6
  • 30
  • 42