Description |
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:
Version 1
In this version, 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.
Version 2
This is similar to version 2, but 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 a version 2 setup, if 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).
Important : 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 final example code.
|
| Related commands | Finally | | Starts the unconditional code section of a Try statement | On | | Defines exception handling in a Try Except clause | Raise | | Raise an exception | Try | | Starts code that has error trapping |
|
Download this web site as a Windows program.
|
|
|
|
Example code : Zero divide with a plain Except block | var
number, zero : Integer;
begin
 // Try to divide an integer by zero - to raise an exception
Try
zero := 0;
number := 1 div zero;
ShowMessage('number / zero = '+IntToStr(number));
Except
ShowMessage('Unknown error encountered');
end;
end;
| Show full unit code | Unknown error encountered | Example code : Divide by zero with an Except On clause | var
number, zero : Integer;
begin
 // Try to divide an integer by zero - to raise an exception
Try
zero := 0;
number := 1 div zero;
ShowMessage('number / zero = '+IntToStr(number));
Except
on E : Exception do
ShowMessage(E.ClassName+' error raised, with message : '+E.Message);
end;
end;
| Show full unit code | EDivByZero error raised with message : Division by zero |
|
|
Delphi Programming © Neil Moffatt . All rights reserved. | Home Page
|
|