Skip to content

Instantly share code, notes, and snippets.

@maxkagamine
Last active January 30, 2025 07:18
Show Gist options
  • Save maxkagamine/6980604bd10c8f3b96fa33c66d0f4ca9 to your computer and use it in GitHub Desktop.
Save maxkagamine/6980604bd10c8f3b96fa33c66d0f4ca9 to your computer and use it in GitHub Desktop.
ExceptionDispatchInfo.Capture(ex.InnerException).Throw() — Example showing how the stack trace changes versus simply rethrowing
using System;
using System.Runtime.ExceptionServices;
class Program
{
static void A()
{
try
{
B();
// if uncaught:
// System.Exception: Oh noes
// ---> System.NotImplementedException: The method or operation is not implemented.
// at Program.C()
// at Program.B()
// --- End of inner exception stack trace ---
// at Program.B()
// at Program.A()
// at Program.Main()
}
catch (Exception ex)
{
throw ex.InnerException;
// System.NotImplementedException: The method or operation is not implemented.
// at Program.A()
// at Program.Main()
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
// System.NotImplementedException: The method or operation is not implemented.
// at Program.C()
// at Program.B()
// --- End of stack trace from previous location ---
// at Program.A()
// at Program.Main()
}
}
static void B()
{
try
{
C();
}
catch (Exception ex)
{
throw new Exception("Oh noes", ex);
}
}
static void C()
{
throw new NotImplementedException();
}
static void Main()
{
A();
}
}