Last active
March 9, 2018 19:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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