Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Response.Redirect(url) in Try / Catch Block

If my response to errors in a try/catch block is to redirect users to an error page, the try/catch block behaves as if there was an error when there was not. If I change it to do something else, the code works fine.

Example:

try
{
    //do this SQL server stuff
}
catch
{
   Response.Redirect(error.htm)
   //Change this to lblErr.Text = "SQL ERROR"; and the code in try works fine.
}

From another post I learned there was a boolean overload to the Response.Redirect() method. I tried both true and false and the try/catch block still behaved as if there were an error.

What's the deal?

like image 618
Nathan McKaskle Avatar asked Feb 16 '26 13:02

Nathan McKaskle


2 Answers

When you Response.Redirect, that throws a ThreadAbortException. So to get the outcome you are describing you'll want to mod your code as follows:

try  
{
   // Do some cool stuff that might break
}
catch(ThreadAbortException)
{

}
catch(Exception e)
{
  // Catch other exceptions
  Response.Redirect("~/myErrorPage.aspx");
}
like image 150
Joshua Avatar answered Feb 19 '26 03:02

Joshua


Response.Redirect("url");

By design this will terminate the calling thread by throwing an exception.

Response.Redirect("url", false);

Will prevent the exception from being thrown, however will allow the code to continue executing.

Using

Response.Redirect("url", false);
HttpContext.Current.ApplicationInstance.CompleteRequest();

Will redirect the user and stop execution without throwing an exception.

like image 22
jon Avatar answered Feb 19 '26 01:02

jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!