|
Given the following code in an .ASPX webforms application :
try
{
Response.Redirect("somePage.aspx");
}
catch (Exception ex)
{
}
finally
{
}
I'm wondering if the code in the Finally block (or any code that might be outside of the whole try/catch) would ever be hit.
Doesn't the Response.Redirect() immediately redirect making any code that follows useless? Or do I just not understand how this works?
|
|
|
|
|
Not trying to be a smart-ass, but why don't you just try it?
Place some dummy code in the finally block and see if it executes. (Use a break-point)
My hunch is that the finally code will execute. Also it may depend on which event the Response-Redirect is placed. (PageLoad, PageInit, ButtonClick, etc)
Post your results, so we all can learn.
|
|
|
|
|
I'm beyond mortified that I didn't think of that. Especially since after posting the question I ran the code to check something else, but putting a break point there just never occurred to me.
Ok, so thanks to David's suggestion I have an answer.
As it is written that code will throw an exception on the Response.Redirect with the following message:
Quote: {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.} However, it still does the redirect after going through the finally block.
Changing the Response.Redirect to
Response.Redirect("SomePage.aspx", false);
will save it from throwing the exception, but will still run the code in the finally and any code after it and then will do the Redirect.
Live and learn.
modified 11-Dec-12 9:26am.
|
|
|
|
|
As you've already figured out, code in the finally block is guaranteed to execute no matter what (unless the runtime host decides otherwise or a system error forcefully terminates the process itself)
|
|
|
|
|
Finally block will always execute, no matter if you redirect your page or throwing some exception.
Finally block will not execution on only Some Exceptions[^]
When you pass 2nd optional Boolean parameter, it indicate whether you would like to complete page execution or just want to redirect page and leave current execution.
Thanks
-Amit Gajjar (MinterProject)
|
|
|
|
|
You already have your answer but to explain Response.Redirect a little more: It is telling the Response object to redirect the user to the new page. What happens is the client gets that message and then requests somePage.aspx. So, it roundtrips but your C# thread will finish. It's essentially just adding a property to the Response object.
Server.Transfer will still finish your C# thread (finally will still run) but the client will not roundtrip. Execution will stay on the server and go to somePage.aspx and execute it and send the Response object back to the client.
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
Very well put. Thanks ryanb31.
|
|
|
|