Try...finally Statements Sometimes you want to ensure that specific parts of an operation are completed, whether or not the operation is
interrupted by an exception. For example, when a routine acquires control of a resource, it is often important that
the resource be released, regardless of whether the routine terminates normally. In these situations, you can use a
try...finally
statement.
The following example shows how code that opens and processes a file can ensure that the file is ultimately closed,
even if an error occurs during execution.
Reset(F);
try
... // process file F
finally
CloseFile(F);
end;
The syntax of a
try...finally
statement is
trystatementList1finallystatementList2end
where each statementList is a sequence of statements delimited by semicolons. The
try...finally
statement
executes the statements in statementList1 (the try clause). If statementList1 finishes without raising exceptions,
statementList2 (the finally clause) is executed. If an exception is raised during execution of statementList1, control
is transferred to statementList2; once statementList2 finishes executing, the exception is re-raised. If a call to the
Exit
,
Break
, or
Continue
procedure causes control to leave statementList1, statementList2 is automatically
executed. Thus the finally clause is always executed, regardless of how the try clause terminates.
If an exception is raised but not handled in the finally clause, that exception is propagated out of the
try...finally
statement, and any exception already raised in the try clause is lost. The finally clause should
therefore handle all locally raised exceptions, so as not to disturb propagation of other exceptions.
165