Description |
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 |
|
|
|
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
|
|
Example code : Divide by zero with multiple Except On clauses |
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));
except // 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
Else
ShowMessage('Unknown error');
end;
end;
|
Show full unit code |
Div by zero error : Division by zero
|
|