23 June 2013

Difference between 'Throw' and 'Throw ex'

Today we are going to compare the difference between 'Throw' and 'Throw ex' with an example. I had created a web project and write the following code:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        int a = 5, b = 0;

        int c = Divide(a, b);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private int Divide(int a, int b)
{
    return a / b;
}

When I run the applicatin it throws exception like this:

 
'Throw ex' basically re-throw the exception and lost the original stack trace. So it is always difficult to track the original stack trace BUT if I replace 'throw ex' to 'throw' like this:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        int a = 5, b = 0;

        int c = Divide(a, b);
    }
    catch (Exception ex)
    {
        throw;
    }
}

private int Divide(int a, int b)
{
    return a / b;
}

Then it will throw exception with original stack trace.

 
 
Key Point: It is better to use 'throw' instead of 'throw ex' where needed BUT observe the above code again. In the above example we are throwing exception in any case and doing nothing inside the catch block THEN why we need try/catch block? In this type of cases it is better to remove try/catch block because we do not need this.

I hope it will clear the difference and also help you to understand invalid usage of try/catch block.

4 comments: