Thursday, 23 February 2017

Difference between throw and throw ex in c#

Throw

In Throw, the original exception stack trace will be retained. To keep the original stack trace information, the correct syntax is 'throw' without specifying an exception.

Declaration of throw


try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw;
}

Throw

In Throw ex, the original stack trace information will get override and you will lose the original exception stack trace. I.e. 'throw ex' resets the stack trace.

Declaration of throw ex


try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw ex;
}
}

Example -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThrowAndThrowEx
{
    class Program
    {
        static void Main(string[] args)
        {
              try{
                    ThrowException1(); // line 19
                } catch (Exception x) {
                    Console.WriteLine("Exception 1:");
                    Console.WriteLine(x.StackTrace);
                }
                try {
                    ThrowException2(); // line 25
                } catch (Exception x) {
                    Console.WriteLine("Exception 2:");
                    Console.WriteLine(x.StackTrace);
                }

                Console.ReadLine();

        }

        private static void ThrowException1()
        {
            try
            {
                DivByZero(); // line 34
            }
            catch
            {
                throw; // line 36
            }
        }
        private static void ThrowException2()
        {
            try
            {
                DivByZero(); // line 41
            }
            catch (Exception ex)
            {
                throw ex; // line 43
            }
        }

        private static void DivByZero()
        {
            int x = 0;
            int y = 1 / x; // line 49
        }
    }
}

Output -



No comments:

Post a Comment