woensdag 11 maart 2009

Throw ex

No, don't throw your ex anywhere. It's just that a collegue mentioned something I didn't know about re-throwing exceptions in .Net.

Say you want to catch an exception and rethrow it after you're done with it:

    Try
      ' try something
    Catch ex As Exception
      ' do something useful
      Throw / Throw ex
    End Try

There's a difference:
- Throw: ex is rethrown, and stack trace is left intact.
- Throw ex: ex is thrown, but stack trace is erased.

So, generally you want to do Throw, not Throw ex.

C# works the same, although with other syntax of course:

            try
            {
                // try something
            }
            catch (Exception ex)
            {
               // do something useful
               throw; / throw ex;
            }

Also see MSDN for an explanation.

Geen opmerkingen: