Take for example the following code:
try
{
Response.Redirect(someurl);
}
finally
{
// Will this code run?
}
Will the code in the finally block run?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Yes.
Try it and see!
Method 2
Simple enough to test:
try
{
Response.Redirect(someurl);
}
finally
{
File.WriteAllText("C:\Temp\test.txt", "The finally block ran.");
}
Method 3
It will run. Response.Redirect actually throws a ThreadAbortException, so that’s why code after that will not run (except anything in a finally block of course).
Method 4
It will indeed. See this MSDN article: Finally always executes
Method 5
The code in the finally will run, but it will run before the redirect, since the redirect won’t be sent to the browser until the method returns, and the finally code will execute before the method returns.
Method 6
Try this:
try
{
Response.Redirect("http://www.google.com");
}
finally
{
// Will this code run?
// yes :)
Response.Redirect("http://stackoverflow.com/questions/3668422/will-code-in-finally-run-after-a-redirect");
}
Method 7
Why do you not just try it?
finally always runs, except in these extreme scenarios:
- Total application crash, or application termination (e.g. FailFast())
- A limited number of serious exceptions
- Threads getting terminated (eg. Thread.Abort())
- Hardware failure (e.g. machine losing power)
- Infinite loop inside the try-block (which ultimately results in application termination)
Method 8
Yes. Code in the finally is guaranteed to run, unless something catastrophic happens.
Method 9
Yes. Here is how you can check if I am right or not. Simply place a message box or write something to the console from finally and you will have your answer.
Method 10
The general rule is that the code in finally will be applied in all cases (try/catch)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0