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

Diffrence between throw and throw ex In this post i will show what is diffrence between throw and throw ex.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionGotcha
{

    public class Foo
    {
        /// <summary>
        /// Method that throw the exception.
        /// </summary>
        public static void MethodWithAttitude()
        {
            throw new ApplicationException();
        }
    }
    class Program
    {
        /// <summary>
        /// 
        /// </summary>
        static void Method()
        {
            try
            {
                Foo.MethodWithAttitude();
            }
            catch (Exception ex)
            {


                throw ex;
            }

        }
        static void Main(string[] args)
        {
            Method();

        }
    }
}
From the above code it is clear that exception is in the Foo class but if you execute this code then it will show exception in Program(Method) class.Where is the problem?.Let's modified the code 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 above code it is clear that there is a diffrence between throw and throw ex
  1. throw ex resets the stack trace (so your errors would appear to originate from some other place)
  2. throw doesn't - the original stack trace would preserved.
  3. At MSIL level throw converted to rethrow

1 comment: