Does the C# "finally" block ALWAYS execute? [duplicate]
Possible Duplicate:
Will code in a Finally statement fire if I return a value in a Try block?
Consider the following code C# code. Does the "finally" block execute?
public void DoesThisExecute() {
string ext = "xlsx";
string message = string.Empty;
try {
switch (ext) {
case "xls": message = "Great choice!"; break;
case "csv": message = "Better choice!"; break;
case "exe": message = "Do not try to break me!"; break;
default:
message = "You will not win!";
return;
}
}
catch (Exception) {
// Handle an exception.
}
finally {
MessageBox.Show(message);
}
}
Ha, after I got done writing this, I realized I could have done tested this myself in Visual Studio. However, please feel free to answer!
No it does not. It will always execute provided the application is still running (except during a FastFail exception, MSDN link, like others noted). It will execute when it exits the try/catch portion of the block.
It will NOT execute if the application crashes: gets killed through a kill process command etc. This is highly important, because if you write code that absolutely expects it to run, like manually doing a roll back, and if not other wise it will automatically commit, you can run into a scenario the application aborts before that happens. Honestly, this is an outside scenario, but it is important to take note of in those situations.
From MSDN C# specification of the try
statement:
The statements of a
finally
block are always executed when control leaves atry
statement. This is true whether the control transfer occurs as a result of normal execution, as a result of executing abreak
,continue
,goto
, orreturn
statement, or as a result of propagating an exception out of thetry
statement.
Source
There are the cases where the finally block will not execute:
- Environment.FailFast
- Uncatchable exception types
- Power Failure