DelphiBasics
Finally
Keyword
Starts the unconditional code section of a Try statement
  Try
    Statement
  {Statement...}
  Finally
    Statement
  {Statement...}
  End;
Description
The Finally keyword is used to mark the start of the final block of statements in a Try statement. They are executed regardless of what happens in the Try statements.
 
However, the Finally clause does not actually handle any exceptions - the program will terminate if no Except clause is found (see notes below).
 
Try-Finally is normally used by a routine to allow cleanup processing to take place, such as freeing resources, with the exception being correctly passed to the caller to handle.
Notes
There are times when you want a construct like this :

Try
  ...
Except
  ...
Finally
  ...
End;


where exceptions are trapped and acted upon, but in all cases, a set of clean up statements are executed. This can be achieved with nested Try statements :

Try
  Try
    ...
  Except
    ...
  End;
Finally
  ...
End;

Related commands
Except Starts the error trapping clause of a Try statement
On Defines exception handling in a Try Except clause
Raise Raise an exception
Try Starts code that has error trapping
 Author links

 Buy Website Traffic at
 Buywebsitetrafficexperts.com

 Buy Proxies at
 Buyproxies.io
 
 Download this web site as a Windows program.


 
Example code : Zero divide with a finally clause
var
  number, zero : Integer;
begin
  // Try to divide an integer by zero - to raise an exception
  number := -1;
  Try
    zero   := 0;
    number := 1 div zero;
    ShowMessage('number / zero = '+IntToStr(number));
  Finally
    if number = -1 then
    begin
      ShowMessage('Number was not assigned a value - using default');
      number := 0;
    end;
  end;
end;
Show full unit code
   Number was not assigned a value - using default
  
   Then, the program terminates with an EDivByZero error message - the finally clause did not trap the error.
 
Delphi Programming Neil Moffatt 2002 - 2016. All rights reserved.  |  Home Page