Skip to content

Instantly share code, notes, and snippets.

@jennings
Last active September 19, 2017 22:42
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/8d75af683a1f392aac780c60f1df4972 to your computer and use it in GitHub Desktop.
Save jennings/8d75af683a1f392aac780c60f1df4972 to your computer and use it in GitHub Desktop.
`throw` vs. `throw ex` in C#

throw ex gives the following stack trace. Notice that THIS_METHOD_THROWS() is missing.

System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at ConsoleApplication1.Program.CatchThrowEx() in C:\Code\ConsoleApplication1\ConsoleApplication1\Program.cs:line 54
   at ConsoleApplication1.Program.Main() in C:\Code\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12

throw gives the following stack trace, which helpfully includes THIS_METHOD_THROWS() where the exception originated.

System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at ConsoleApplication1.Program.THIS_METHOD_THROWS() in C:\Code\ConsoleApplication1\ConsoleApplication1\Program.cs:line 60
   at ConsoleApplication1.Program.CatchThrow() in C:\Code\ConsoleApplication1\ConsoleApplication1\Program.cs:line 42
   at ConsoleApplication1.Program.Main() in C:\Code\ConsoleApplication1\ConsoleApplication1\Program.cs:line 24
using System;
namespace ConsoleApplication1
{
public class Program
{
public static void Main()
{
try
{
Console.WriteLine("THROW EX:");
CatchThrowEx();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine();
try
{
Console.WriteLine("THROW:");
CatchThrow();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
static void CatchThrowEx()
{
try
{
THIS_METHOD_THROWS();
}
catch (Exception ex)
{
throw ex;
}
}
static void CatchThrow()
{
try
{
THIS_METHOD_THROWS();
}
catch (Exception)
{
throw;
}
}
static void THIS_METHOD_THROWS()
{
throw new InvalidOperationException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment