Translate

Monday, 15 December 2014

Difference between “Throw” and “Throw ex”?

“Throw” propagates the full stack information to the caller, while “Throw ex” excludes stack information from the point where you called “Throw ex”.
For instance let’s say you have a “Main” method which calls “Method2” and “Method2” calls “Method1”. Now in “Method2” if you handle exception by using just “Throw”, it will propagate the complete stack error to the main method.
If you add “ex” i.e. if you use “Throw ex” it will propagate stack information only from “Method2”.



Example:

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MethodA();
            }
            catch (Exception ex)
            {
                //Showing overridden exception stack with MethodA instead of MethodB on top
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }

        private static void MethodA()
        {
            try
            {
                MethodB();
            }
            catch (Exception ex)
            {
                //Overrides original stack trace
                throw ex;
            }
        }

        private static void MethodB()
        {
            throw new NotImplementedException();
        }
    }
}


No comments:

Post a Comment