Throw Trap
Often, in exception handling, we would need to re-throw an exception caught in the catch block, after doing some operation (logging the exception, for instance). But, we generally make the mistake of providing the exception argument in the throw expression. The problem is that, in this case, we might lose the original call stack. Here's a small snippet to give you the idea:
static void exA()
{
try
{
exB();
}
catch(Exception ex)
{
//Watch out!
//throw ex;
//Better
throw;
}
}
static void exB()
{
throw new Exception("New Exception");
}
static void Main(string[] args)
{
try
{
exA();
}
catch(Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
If we were to do a throw ex in the above snippet, then we would have the following stacktrace. Note that we have lost exB() in the stack trace.
exA()
Main(String[] args)
If we were to just re-throw the exception, then we would have got the entire stack trace
exB()
exA()
Main(String[] args)
For more information refer to the C# Language Specification and Lance Hunt's C# Coding Guidelines for .NET.