Say, I have a try/catch block that encapsulates a large block of code and then somewhere in it I need to call Response.Redirect as such:
protected void ButtonGo_Click(object sender, EventArgs e)
{
try
{
using(lockingMethod)
{
//Code...
//Somewhere nested in the logic
Response.Redirect(strMyNewURL);
//More code...
}
}
catch(Exception ex)
{
LogExceptionAsError(ex);
}
}
What happens in this case is that Response.Redirect
throws an exception, something about terminating the thread, which I believe is a "normal flow of events" for that method, but it gets logged in my LogExceptionAsError
as an error. So I was curious, is there any way to make Response.Redirect
not throw exception?
Response.Redirect
accomplishes termination of the current execution and thus immediate redirection via throwing this exception such that it is unhandled. This is intentional and by design. You should not be catching it yourself in most cases - it defeats the purpose. If you wish to complete executing your code before redirecting, you can use the overload:
Response.Redirect(somewhere, false);
Which will NOT raise the exception. This could be inefficient unless you NEED to do something else before redirecting.
Note that this is generally an anti-pattern - controlling logic flow via exception throwing and catching... However it makes sense for this particular method to do so since a redirect usually requires no further logic to execute - just responds with a 302 and the new address to go to.
Try with alternative version of Response.Redirect
Response.Redirect(strMyNewURL, false);
It will terminate the current page loading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With