Skip to content

Instantly share code, notes, and snippets.

@jennings
Last active March 9, 2018 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jennings/a700e0c884c043c1a30ae5969148e01c to your computer and use it in GitHub Desktop.
Save jennings/a700e0c884c043c1a30ae5969148e01c to your computer and use it in GitHub Desktop.
Demonstrates how `throw ex` replaces the stack trace in an exception, while `throw` preserves it.
using System;
class Program
{
static void One() { Two(); }
static void Two() { Three(); }
static void Three() { throw new Exception("Error"); }
static void Main(string[] args)
{
Console.WriteLine("RE-THROWING AN EXCEPTION WITH `throw ex`");
CatchExceptionAndPrintToConsole(() =>
{
try { One(); }
catch (Exception ex) { throw ex; }
});
Console.WriteLine("\n\nRE-THROWING AN EXCEPTION WITH `throw`");
CatchExceptionAndPrintToConsole(() =>
{
try { One(); }
catch (Exception) { throw; }
});
Console.WriteLine("\n\nPress any key to exit");
Console.ReadKey();
}
static void CatchExceptionAndPrintToConsole(Action action)
{
try { action(); }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment