what can lead throw to reset a callstack (I'm using "throw", not "throw ex")

Brann picture Brann · Mar 1, 2011 · Viewed 7.9k times · Source

I've always thought the difference between "throw" and "throw ex" was that throw alone wasn't resetting the stacktrace of the exception.

Unfortunately, that's not the behavior I'm experiencing ; here is a simple sample reproducing my issue :

using System;
using System.Text;

namespace testthrow2
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                try
                {
                    throw new Exception("line 14");
                }
                catch (Exception)
                {
                    throw; // line 18
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

            }
            Console.ReadLine();
        }
    }
}

I would expect this code to print a callstack starting at line 14 ; however the callstack starts at line 18. Of course it's no big deal in the sample, but in my real life application, losing the initial error information is quite painful.

Am I missing something obvious? Is there another way to achieve what I want (ie re throwing an exception without losing the stack information?)

I'm using .net 3.5

Answer

Justin picture Justin · Mar 1, 2011

You should read this article:

In short, throw usually preserves the stack trace of the original thrown exception, but only if the exception didn't occur in the current stack frame (i.e. method).

There is a method PreserveStackTrace (shown in that blog article) that you use that preserves the original stack trace like this:

try
{

}
catch (Exception ex)
{
    PreserveStackTrace(ex);
    throw;
}

But my usual solution is to either simply to not catch and re throw exceptions like this (unless absolutely necessary), or just to always throw new exceptions using the InnerException property to propagate the original exception:

try
{

}
catch (Exception ex)
{
     throw new Exception("Error doing foo", ex);
}