Tech Off Post

Single Post Permalink

View Thread: other fun stuff about exceptions
  • atehrani

    Far too many times I see incorrect exception rethrowing in C#.


    "Re-throwing" an exception like this is incorrect, as the stack trace will be reset.

    catch ( FooException ex )
    {
           throw ex; // WRONG Sad
    }



    This is the correct way to rethrow an exception.

    catch ( FooException ex )
    {
           throw; // CORRECT Smiley
    }


    Please note that a trace of the stack is only taken when the "throw" keyword is executed. In Java the stack trace is taken when an exception is instantiated. This is a subtle but large difference.