17.3 The try...finally statement

A Try..Finally statement has the following form:

_________________________________________________________________________________________________________
Try...finally statement

--try-finally-statement -try -statement- list- finally -finally- statements-end ----

--finally- statements-statement- list------------------------------------
___________________________________________________________________

If no exception occurs inside the statement List, then the program runs as if the Try, Finally and End keywords were not present, unless an exit command is given: an exit command first executes all statements in the finally blocks before actually exiting.

If, however, an exception occurs, the program flow is immediately transferred from the point where the exception was raised to the first statement of the Finally statements.

All statements after the finally keyword will be executed, and then the exception will be automatically re-raised. Any statements between the place where the exception was raised and the first statement of the Finally Statements are skipped.

As an example consider the following routine:

Procedure Doit (Name : string);  
Var F : Text;  
begin  
  Assign (F,Name);  
  Rewrite (name);  
  Try  
    ... File handling ...  
  Finally  
    Close(F);  
  end;  
end;

If during the execution of the file handling an exception occurs, then program flow will continue at the close(F) statement, skipping any file operations that might follow between the place where the exception was raised, and the Close statement. If no exception occurred, all file operations will be executed, and the file will be closed at the end.

Note that an Exit statement enclosed by a try .. finally block, will still execute the finally block. Reusing the previous example:

Procedure Doit (Name : string);  
Var  
  F : Text;  
  B : Boolean;  
begin  
  B:=False;  
  Assign (F,Name);  
  Rewrite (name);  
  Try  
    // ... File handling ...  
    if B then  
      exit; // Stop processing prematurely  
    // More file handling  
  Finally  
    Close(F);  
  end;  
end;

The file will still be closed, even if the processing ends prematurely using the Exit statement.