Information Technology Reference
In-Depth Information
The finally Block
If a program's flow of control enters a
try
statement that has a
finally
block, the
finally
block
is
always
executed. The flow of control is illustrated in Figure 11-5.
If no exception occurs inside the
try
block, then at the end of the
try
block, control goes
to the
finally
block—skipping over any
catch
clauses.
If an exception occurs inside the
try
block, then any appropriate
catch
clauses in the
catch
clauses section are executed, followed by the
finally
block.
Figure 11-5.
Execution of the finally block
Even if a
try
block has a
return
statement, the
finally
block will still always be executed
before returning to the calling code. For example, in the following code, there is a
return
state-
ment in the middle of the
try
block that is executed under certain conditions. This does not
allow it to bypass the
finally
statement.
try
{
if (inVal < 10) {
Console.Write("First Branch - ");
return;
}
else
Console.Write("Second Branch - ");
}
finally
{ Console.WriteLine("In finally statement"); }
This code produces the following output when variable
inVal
has the value
5
.
First Branch - In finally statement