Friday, January 18, 2013

Throw vs Throw Ex

What is the difference between throw and throw ex in C#?

See below direct point of the actual difference of throw and throw ex.

Throw Ex

Basically, throw ex command resets the stack trace and will clear any originated exception from handled exception. You will see that the StackTrace value will be cleared and it will only include the exception that was thrown. Catching different type of exception will also differ the results. See below the code.

namespace CodesDirectory
{
    public partial class WIN_ThrowThrowEx : Window
    {
        public WIN_ThrowThrowEx()
        {
            InitializeComponent();
            try
            {
                this.ErrorMethod();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0}\nStack: {1}", ex.Message, ex.StackTrace), "Original Message");
            }
        }

        public void ErrorMethod()
        {
            try
            {
                this.DivideError();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public int DivideError()
        {
            var x = 0;
            return 1 / x;
        }
    }
}

You will notice we throw the exception object in yellow background. The result is below.

   at CodesDirectory.WIN_ThrowThrowEx.ErrorMethod() in C:\Users\mpendon\Documents\Visual Studio 2010\Projects\CodesDirectory\WIN_ThrowThrowEx.xaml.cs:line 40
   at CodesDirectory.WIN_ThrowThrowEx..ctor() in C:\Users\mpendon\Documents\Visual Studio 2010\Projects\CodesDirectory\WIN_ThrowThrowEx.xaml.cs:line 24

Throw

However, if you however change the throw ex to only throw. Then the result is below.

   at CodesDirectory.WIN_ThrowThrowEx.DivideError() in C:\Users\mpendon\Documents\Visual Studio 2010\Projects\CodesDirectory\WIN_ThrowThrowEx.xaml.cs:line 47
   at CodesDirectory.WIN_ThrowThrowEx.ErrorMethod() in C:\Users\mpendon\Documents\Visual Studio 2010\Projects\CodesDirectory\WIN_ThrowThrowEx.xaml.cs:line 40
   at CodesDirectory.WIN_ThrowThrowEx..ctor() in C:\Users\mpendon\Documents\Visual Studio 2010\Projects\CodesDirectory\WIN_ThrowThrowEx.xaml.cs:line 24

So please always catch the exception and just simply call the throw instead of throw ex so it would not affect any debugging session of the user. Our advice is to let you just use throw command.

No comments:

Post a Comment

Place your comments and ideas