Difference between “throw” and “throw ex”

Have you ever wonder what’s difference between “throw ex” and “throw’?  I used to do “throw ex” from inside catch block rather than “throw”.  But it’s really need to know the different between those two.

Let’s create a sample web application.

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        GenerateSomeException();

        int i = 10;
        int j = 10 / i;
     }
     catch (Exception ex)
    {
     throw ex;
     }
}

private void GenerateSomeException()
{

int i = 0;
int j = 100 / i;

}

I created “GenerateSomeException” method to generate “DivideByZeroExcception” exception.  I called that method from Page_Load event and wrap that method call in try catch block.   In catch block I just raise the exception that got caught.  Now run the sample web application and you will see the following error stack trace.

}

Look closely the line I have highlighted with red color.   In “Source Error” section, .net shows you the error is at “throw ex” line and in “Stack Trace” error is shown in Page_Load event.  But the error we generated in “GenerateSomeException” method not in Page_Load event.

Now let’s use “throw” statement rather than “throw ex” statement and see what’s error stack trace is generated.
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
       GenerateSomeException();

       int i = 10;
       int j = 10 / i;
     }
     catch (Exception ex)
     {
         throw;
     }
}

private void GenerateSomeException()
{

int i = 0;
int j = 100 / i;

}
Now run the above code.  You will see below yellow screen.

It shows you the error in “GenerateSomeException” method.  This is the exact location where the error is.

If you use “throw” statement, it preserve original error stack information.
If you use “throw ex” statement, stack trace of the exception will be replaced with a stack trace starting at the re-throw point.

So it is very important to just use the throw statement, rather than throw ex because it will give you more accurate error stack information.

Posted in Microsoft Technology Tagged with:
One comment on “Difference between “throw” and “throw ex”
  1. Shaun says:

    Great info, now onwards I will also “thow;” only.

Ads