Darshana
Darshana

Reputation: 2548

Exception thrown by page redirection in asp.net

I have this code

protected void Button_Click(object sender, EventArgs e)
{
    try
    {
        // some code

        con.Open();
        string result = command.ExecuteScalar().ToString();

        if (result != string.Empty)
        {
             // some code
             Response.Redirect("Default.aspx");
        }
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
    finally
    {
        con.Close();
    }

It gives an exception from Response.Redirect("Default.aspx");

ex: Thread was being aborted.

any idea why?

thanx

Upvotes: 2

Views: 1136

Answers (2)

Tim B James
Tim B James

Reputation: 20364

Redirecting from within a Try...Catch statement will result in this Exception being thrown, so this is not what you want to do.

I would update your code to;

string result = string.Empty;

try
{
    // some code
    con.Open();
    result =  command.ExecuteScalar().ToString();        
}
catch (Exception ex)
{
    throw new Exception(ex.Message);
}
finally
{
    con.Close();
}

if (result != string.Empty)
{
     // some code
     Response.Redirect("Default.aspx");
}

Upvotes: 2

Martin
Martin

Reputation: 16423

This is a typical Exception that is thrown by ASP.NET when performing a redirect. It's quite well documented on the Interweb.

Try the following catch block to swallow the exception and all should be fine. It's supposed to do nothing!

catch(ThreadAbortException)
{
}
catch (Exception ex)
{
    throw new Exception(ex.Message);
}
finally
{
    con.Close();
}

Upvotes: 0

Related Questions