2

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

Daniele Armanasco
  • 7,289
  • 9
  • 43
  • 55
Darshana
  • 2,462
  • 6
  • 28
  • 54

2 Answers2

2

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");
}
Tim B James
  • 20,084
  • 4
  • 73
  • 103
0

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();
}
Martin
  • 16,093
  • 1
  • 29
  • 48
  • I would avoid swallowing exceptions - even when in this case there's no obvious side effects, it's a bad habit to get into, IMO. There are better ways to handle it - for example Tim B James answer below. – Tim Mar 14 '13 at 16:29