1

I have seen Exception Handling blocks that they were throwing the recently caught Exception in the catch block. Something like:

} catch ( Exception $e ) {
    // Do some recovery here
    callSomeFunction();

    throw $e;
}

To me it doesn't make that much sense to throw the exact same Exception like this, but I'm not sure if I'm right or not. Maybe there are situations that that's the only option?

My question is what are the pros and cons of this approach and shouldn't it be totally avoided as much as possible?

gnat
  • 21,442
  • 29
  • 112
  • 288
Mahdi
  • 1,983
  • 2
  • 15
  • 25
  • 1
    related: [Is rethrowing an exception leaking an abstraction?](http://programmers.stackexchange.com/questions/132612/is-rethrowing-an-exception-leaking-an-abstraction) – gnat Mar 05 '14 at 08:36
  • @gnat Again it was really interesting; However I couldn't find any clean answer about the re-throwing the exception. Please let me know if I'm missing something there. Thanks again. – Mahdi Mar 07 '14 at 07:46
  • 1
    you didn't miss anything, your question is ok ([duplicates are generally considered ok at Stack Exchange](http://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/)). Question about try / catch block usage is simply more general and answers to it provide more guidance which is applicable to questions like this one – gnat Mar 07 '14 at 07:56
  • 1
    @gnat Oh, great! – Mahdi Mar 07 '14 at 08:03

1 Answers1

2

Sometimes you have more information right on hand, like intermediate values, that you can do something with. A lot of times you can log that information, if nothing else.

You can also attempt recovery or backout before altering the caller that something went wrong.

But, ultimately, if the code can't complete its use case and needs to halt, then ya performing mitigation or reporting can be useful before re-throwing the error.

The problem is, what if the mitigation fails? The nested exception handling can get hairy. So I'm with you; I'll sometimes handle & re-throw the error, but I will also think hard about my design.

sea-rob
  • 6,841
  • 1
  • 24
  • 47