Difference between "throw" and "throw ex" in .NET

This post will show the difference between throw and throw ex is.Exception handling is the most critical part of programming. If the Exception is not handled correctly, it will cost the company and take time to troubleshoot the issue.


public class Foo
{
	public static void MethodWithAttitude()
	{
		throw new ApplicationException();
	}
}
class Program
{
	static void Method()
	{
		try
		{
			Foo.MethodWithAttitude();
		}
		catch (Exception ex)
		{

			throw ex;
		}
	}
	static void Main(string[] args)
	{
		try
		{
			Method();
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex);
		}

	}
}


The Exception is in the Foo class from the above stack trace, but it is showing Exception in Program(Method) class. Where is the problem?. Let’s modify the code a little bit; instead of throw ex put throw and instead of Exception ex put Exception and then execute the code, it will show Exception in Foo class. From the above code, it is clear that there is a difference between throw and throw ex

static void Method()
	{
		try
		{
			Foo.MethodWithAttitude();
		}
		catch (Exception)
		{

			throw;
		}
	}

As per the Microsoft

Once an exception is thrown, part of the information it carries is the stack trace. The stack trace is a list of the method call hierarchy that starts with the method that throws the Exception and ends with the method that catches the Exception. Suppose an exception is re-thrown by specifying the Exception in the throw statement. In that case, the stack trace is restarted at the current method, and the list of method calls between the original method that threw the Exception and the current method is lost. To keep the original stack trace information with the Exception, use the throw statement without specifying the Exception.

Let’s summarize till now.

  1. throw ex resets the stack trace (so your errors would appear to originate from some other place)
  2. The throw preserve the original stack trace and rethrow
    There is no such keyword rethrow in C#, but you know that C# generates MSIL, which is the code CLR executes. Let’s see the MISL generated code when we used throw only. As you can in the below image that throw is converted to rethrow in MSIL

Conclusion

Now you know the difference between throw and throw ex. If you want to add extra information to the original stack trace, you can use the following approach.

static void Method()
	{
		try
		{
			Foo.MethodWithAttitude();
		}
		catch (Exception ex)
		{

			throw new Exception("Exception caught rethrowing with extra information",ex);
		}
	}

If you don’t want to handle the Exception, then you can use the following approach.

static void Method()
	{
		try
		{
			Foo.MethodWithAttitude();
		}
		catch (Exception ex)
		{

			throw;
		}
	}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post