0

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();
 }
arkabhi
  • 68
  • 5
  • 1
    If an exception knows what to do when being thrown, there is no point in throwing an exception: you could not throw it at all and directly do what needs to be done. The point of an exception is to signal an exceptional situation, and let the caller decide what to do in that case. – JB Nizet Jun 30 '15 at 10:15
  • Further, `catch` blocks should never ever do anything beyond reporting an exception. If there is something that needs to be done (closing a database or connection), then use the `finally` block. – Rossiar Jun 30 '15 at 10:18
  • Have edited my question, with alternatives. Is it good practice to have handling logic within an exception class? – arkabhi Jun 30 '15 at 10:25

1 Answers1

0

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.

Jocke
  • 414
  • 3
  • 6
  • Thanks. No, I am not using them to drive the expected behavior. They just wrap over the already occurred run-time exceptions. – arkabhi Jun 30 '15 at 10:52