except
The Except keyword is used to mark the start of a block of statements
that handle an exception in a Try clause. If the Except block can handle
the exception, then the program is not terminated.
Except has two different syntaxes:
Syntax 1
If the Try clause generates an exception the Except clause is executed.
This is used to take alternative action when something unexpected goes
wrong. The except clause cannot determine the error type however.
Syntax 2
This syntax specifies different actions for different exception types,
such as EInOutError. An Else clause can be used as a catch all for unexpected
exception types. The general exception type Exception can be used to catch
all exception types.
By assigning a Name to the exception, the message text of the exception
(Name.Message) can be obtained for display or other uses.
When an exception is raised in this setup, and the exception is not acted
upon by On or Else statements, then a check is made to see if we are in a
nested Try block. If so, the Except clause of this parent Try is processed.
If no On or Else clause is found, the program terminates.
The Else clause is not really necessary - it is better to use On E:Exception Do,
the generic exception handling, since it still provides the error message (E.Message).
Note: You can determine the type of error that occured by using the generic
exception handling - On E:Exception Do. E is a pointer to the exception object that
is created by the exception condition. E.ClassName gives the exception type, such
as 'EDivByZero', as shown in the 2nd part of the example code.
Example
Download This Source for Free Pascal
{$MODE DELPHI} // Enable Try/Except keywords
uses
SysUtils; // Defines "exception" type
var
number, zero : Integer;
begin
// Try to divide an integer by zero - to raise an exception
Try
zero := 0;
number := 1 div zero;
Writeln('number / zero = ',number);
Except
Writeln('Unknown error encountered');
end;
// Try to divide an integer by zero - to raise an exception
Try
zero := 0;
number := 1 div zero;
Writeln('number / zero = ',number);
Except
on E : Exception do
Writeln(E.ClassName,' error raised, with message : ',E.Message);
end;
end.
Output
Unknown error encountered
EDivByZero error raised, with message : Division by zero
See Also
Finally,
On,
Raise,
Try.