Tuesday, May 18, 2010

.net difference between throw and throw ex

  • stack information is truncated if we are using throw ex
  • where as stack information gets preserved in throw

throw ex - throw
throw  - rethrow


class Program
    {
        static void Main(string[] args)
        {
            A aa = new A();
            aa.Method1();
        
            Console.Read();
        }
    }

    class A
    {
        public void Method1()
        {
            try
            {
                B bb = new B();
                bb.Method2();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
    }

    class B
    {
        public void Method2()
        {
            try
            {
                C cc = new C();
                cc.Method3();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    class C
    {
        public void Method3()
        {
            try
            {
                throw new InvalidOperationException();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }
    }
 


throw
at CatchSample.C.Method3() in C:\temp\oops\oops\CatchSample\Program.cs:line 60
at CatchSample.B.Method2() in C:\temp\oops\oops\CatchSample\Program.cs:line 45
at CatchSample.A.Method1() in C:\temp\oops\oops\CatchSample\Program.cs:line 25

throw ex
at CatchSample.B.Method2() in C:\temp\oops\oops\CatchSample\Program.cs:line 45
at CatchSample.A.Method1() in C:\temp\oops\oops\CatchSample\Program.cs:line 25

NoteStackTrace information is lost in case of throw ex


Reference:

http://aspadvice.com/blogs/joteke/archive/2004/04/15/2277.aspx

http://geekswithblogs.net/sdorman/archive/2007/08/20/Difference-between-quotthrowquot-and-quotthrow-exquot-in-.NET.aspx

No comments: