Defines exception handling in a Try Except clause
    On {Name :} Exception type Do Statement;
  {Else Statement}
The On keyword defines an exception handling statement in the Except part of a Try statement.
If the specified Exception is raised in the Try statements, then the Do statement is executed.
By assigning a Name to the exception, the message text of the exception (Name.Message) can be obtained for display or other uses.
If the exception raised finds no matching On clause, 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).
For all exceptions, an Exception object is created, and it is this that is referenced in the On clause. These objects are normally derived from the Exception class.
You can determine the type of exception that occured by looking at the ClassName property, which gives the exception type, such as 'EDivByZero', as shown in the example code.
Related commands
Except Starts the error trapping clause of a Try statement
Finally Starts the unconditional code section of a Try statement
Raise Raise an exception
Try Starts code that has error trapping
 Author links

 Buy Website Traffic at

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

Example code : Divide by zero with an Except On clause
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
unit Unit1;
  Forms, Dialogs;
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
Form1: TForm1;
{$R *.dfm} // Include form definitions
procedure TForm1.FormCreate(Sender: TObject);

  number, zero : Integer;
  // Try to divide an integer by zero - to raise an exception
    zero   := 0;
    number := 1 div zero;
    ShowMessage('number / zero = '+IntToStr(number));
    On E : Exception do
      ShowMessage(E.ClassName+' error raised, with message : '+
Hide full unit code
   EDivByZero error raised with message : Division by zero
Example code : Divide by zero with multiple Except On clauses
  number, zero : Integer;
  // Try to divide an integer by zero - to raise an exception
  number := -1;
    zero   := 0;
    number := 1 div zero;
    ShowMessage('number / zero = '+IntToStr(number));
    // Our first exception will not be nmatched
    On E : EInOutError do
      ShowMessage('IO error : '+E.Message);
    // This exception will be matched
    On E : EDivByZero do
      ShowMessage('Div by zero error : '+E.Message);
    // Catch other errors
      ShowMessage('Unknown error');
Show full unit code
   Div by zero error : Division by zero
Delphi Programming Neil Moffatt 2002 - 2017. All rights reserved.  |  Home Page