title: Attach StackTrace To Exception Without Throwing in C# / .NET
body: <p>I have a component which handles errors using return values as opposed to standard exception handling. In addition to the error code, it also returns a stack trace of where the error has occurred. A wrapper I use to invoke the component will interpret return codes and throw an exception.</p>
  <p>I'd like to have the wrapper throw an exception that includes the captured stack trace information from the component. I'd like it to appear as if the exception had been thrown from the original site of the error even though it was thrown elsewhere. <em>More specifically, I'd like the stack trace displayed by the Visual Studio test runner to reflect the proper location.</em></p>
  <p>Is there any way to do this? It would also be nice if I could avoid low-level reflection tricks accessing private members but I will take what I can get.</p>
  <p>I'm not concerned with how to capture a stack trace, I'm concerned with attaching a stack trace that's already been captured, to an Exception.</p>
  <p>I tried overriding the StackTrace property, but Visual Studio is pulling the stack trace data from somewhere else, and seems to ignore the overridden property completely</p>
  <pre><code>CustomException GenerateExcpetion()
  {
      return new CustomException();
  }
  
  void ThrowException(Exception ex)
  {
      Trace.WriteLine(&quot;Displaying Exception&quot;);
      Trace.WriteLine(ex.ToString());
      var edi = ExceptionDispatchInfo.Capture(ex);
      edi.Throw();
  }
  
  [TestMethod]
  public void Test006()
  {
      var ex = GenerateExcpetion();
      ThrowException(ex);
  }
  
  public class CustomException : Exception
  {
      string _stackTrace;
      public CustomException()
      {
          _stackTrace = Environment.StackTrace;
      }
  
      public override string StackTrace
      {
          get
          {
              return base.StackTrace;
          }
      }
  }
  </code></pre>
  <p>The <code>Exception.ToString()</code> method pulls stack trace data from a private property, and so the stack trace coming from the override doesn't get shown.</p>
  <p>CustomException: Exception of type 'CustomException' was thrown.</p>
  <p>The ExceptionDispatchInfo looks for the stack trace data from a private property as well, and so it can't find any of that data, and when you throw this custom exception a new stack trace is attached to the exception with the location that it is being thrown from. If you use throw directly, the private stack information is set to the place where the throw happened.</p>