Wednesday, 19 November 2014

Difference between Throw and Throw ex in C# Asp.Net


In day to day development, we all are very familiar with Exception handling. We pretty much all know that we should wrap the code which may cause for any error in try/catch block and do something about error like give an error message to end user.

Throw

In Throw, the original exception stack trace will be retained. To keep the original stack trace information, the correct syntax is 'throw' without specifying an exception.


try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw;
}

Throw ex

In Throw ex, the original stack trace information will get override and you will lose the original exception stack trace. I.e. 'throw ex' resets the stack trace.

try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw ex;
}
}

No comments:

Post a Comment