24

Is there a difference between just saying throw; and throw ex; assuming ex is the exception you're catching?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Westbrook
  • 1,960
  • 5
  • 23
  • 35

3 Answers3

44

throw ex; will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use throw;

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
  • I have never seen one, although there might be. As stated below, I have heard of attaching it to the innerexception, but I can think of no reason you would want to destroy your stack trace. – GEOCHET Sep 18 '08 at 00:14
18

Here is a simple code snippet that will help illustrate the difference. The difference being that throw ex will reset the stack trace as if the line "throw ex;" were the source of the exception.

Code:

using System;

namespace StackOverflowMess
{
    class Program
    {
        static void TestMethod()
        {
            throw new NotImplementedException();
        }

        static void Main(string[] args)
        {
            try
            {
                //example showing the output of throw ex
                try
                {
                    TestMethod();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine();
            Console.WriteLine();

            try
            {
                //example showing the output of throw
                try
                {
                    TestMethod();
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.ReadLine();
        }
    }
}

Output (notice the different stack trace):

System.NotImplementedException: The method or operation is not implemented.
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23

System.NotImplementedException: The method or operation is not implemented.
at StackOverflowMess.Program.TestMethod() in Program.cs:line 9
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43

Eric Schoonover
  • 47,184
  • 49
  • 157
  • 202
2

You have two options throw; or throw the orginal exceptional as an innerexception of a new exception. Depending on what you need.