2

Is there any valid reason why a catch block on a lower layer would throw back an exception caused by a higher, unknown layer using the following syntax:

throw ex;

... rather than:

throw;

... ?

In the first case, not only the catch block doesn't deal with the exception, but it also reset its StackTrace property, making it more difficult to understand what caused it.

Why would anyone want a catch block in a lower layer to behave like this?

2
  • What do you mean by "caused by a higher layer?" Like in a callback? Nov 27, 2014 at 1:17
  • @KarlBielefeldt a callback, an event handler, an overriden method... pretty much anything that can execute code outside the assembly boundaries. The chain of methods originates from within the try block.
    – Crono
    Nov 27, 2014 at 3:16

1 Answer 1

1

First off, having a catch block which only rethrows the exception is usually useless. But, the only real world scenario i can think of which makes sense to use throw ex instead of throw is if you're developing some sort of third party library which you by all means dont want anyone in the outter scope who's using your code to see the full stacktrace. Im not saying this is a good thing, but it might happen.

3
  • We agree that it's pointless to try and hide away this information when A) it's always possible to catch first-chance exceptions and B) the exception can still be caught from where it was first thrown?
    – Crono
    Nov 26, 2014 at 20:58
  • It is just to reduce confusion. If the API writer knows where the exception comes from, they are reinterpreting it in a more "API friendly" way, so the API user does not have to wonder so much. Since you are wondering why anyone would do this, I doubt you are encountering this problem in a friendly library. Nov 27, 2014 at 2:08
  • @FrankHileman I'm actually encountering this behavior with a 3rd party UI control library, which I won't name here. It catches exceptions thrown from event handlers then throws it back using throw ex syntax.
    – Crono
    Nov 27, 2014 at 3:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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