Search code examples
javaexceptioncustom-exceptions

Where to have the Handlers for Custom Exceptions


I have 2 custom exceptions defined in my project. Each of which should be handled differently.

Exception A
{
   errCode
}
Exception B
{
  // other stuff
   errCode
}

The main caller method, is like this.

Should the code to write into the tables be within the exception class (say a method called handleItself() ). Or should the caller method handle it?

There are multiple entry points. And I am hesitant to have the handling logic lying around everywhere.

Which is the better way?

 catch (A a)
 {
   insert to table X
 }
 catch (B b)
 {
    // do other stuff
    insert to table Y
 } 

             or
 catch (A a)
 {
    a.handleItself();
 }
 catch (B b)
 {
    // do other stuff
    b.handleItself();
 }

Solution

  • It's good practice to not include any business logic in exceptions, they should be dumb objects only carrying information about the reason for them being thrown. It is the catching class that is responsible (and in most of the case, able) to decide what to do with it.

    Judging from the nature of this question, it seems as though you are using exceptions the wrong way. Exceptions are just that, exceptions, and should not be used to drive the expected (read normal) behavior of the software.