Response.Redirect exception inside the try/catch block
Solution 1
Try with alternative version of Response.Redirect
Response.Redirect(strMyNewURL, false);
It will terminate the current page loading.
Solution 2
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.
Related videos on Youtube
c00000fd
You can contact me at webdc2000 [ a t ] hotmail.com
Updated on September 14, 2022Comments
-
c00000fd over 1 year
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 myLogExceptionAsError
as an error. So I was curious, is there any way to makeResponse.Redirect
not throw exception?-
Kevin Nacios over 10 yearspossible duplicate of Is there something that prevents Response.Redirect to work inside try-catch block?
-
-
c00000fd over 10 yearsEvently
catch(ThreadAbortException)
will also catch it. I'm not clear though on how to handle it? -
sarwar026 over 10 years@c00000fd: I am not sure about that :(
-
c00000fd over 10 yearsOK. I just stepped through with a debugger. The
ThreadAbortException
is indeed caught whenResponse.Redirect
is processed. So if the handler is left empty, the CLR will take over then. -
cockypup about 9 yearsGreat explanation! I have to say, though, my programming 101 teacher would have failed me if I would have use this fetching "technique". Exceptions are meant to flag bad things, not as an easy way to "drop it all and leave the room". Bad Microsoft.