1

This question already has an answer here:

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?

marked as duplicate by gnat, Bart van Ingen Schenau, user40980, GlenH7, Dynamic Mar 7 '14 at 21:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
  • @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 7 '14 at 7:46
  • 1
    you didn't miss anything, your question is ok (duplicates are generally considered ok at Stack Exchange). 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 7 '14 at 7:56
  • 1
    @gnat Oh, great! – Mahdi Mar 7 '14 at 8:03
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.

  • 1
    Exception handling is tough! :) – Rob Mar 5 '14 at 7:35
  • Yeap, because they're all Exceptions! – Mahdi Mar 5 '14 at 8:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.