Brilliant exception handling I found in an app i had to work on

  • @[email protected]
    link
    fedilink
    52 years ago

    Rethrowing caught exception in C# is just throw;, not throw ex;. This will delete old stack trace, which is very punishable if someone debugs your code later and you’re still around.

    • @bartimeo
      link
      12 years ago

      I am a somewhat new C# developer (2 years). Could you explain more about this?

      • @CatPoop
        link
        1
        edit-2
        2 years ago

        An exception will bubble up the stack until it enters a catch block that can handle it, and you may need additional logic to decide if you are finished, or it needs to go further up. (you may also intercept it just to add more data, or log it)

        throw; allows you send the original exception further up, but throw ex; behaves the same as throwing a new Exception object, and therefore has a new trace. The throw statement doesn’t query any properties on the exception argument AFAIK, so it has no idea this exception has been previously thrown, but the IDE is smart enough to know you almost certainly don’t want to do this.

      • @[email protected]
        link
        fedilink
        12 years ago

        throw ex; treats ex as a new exception, so, it starts a new stack trace for it from itself and deletes stack trace that was saved in ex.StackTrace. On the other hand, throw; takes already present exception in the scope and throws it without modifying the stack trace, preserving the original method that threw ex in the stack trace.

        I feel like I wrote the same thing twice. I’m a bit bad with explaining stuff, feel free to ask more specific questions if you still don’t understand the difference.