Quick start manual
7-30
Delphi Language Guide
Exceptions
Try...except statements
Exceptions are handled within try...except statements. For example,
try
X := Y/Z;
except
on EZeroDivide do HandleZeroDivide;
end;
This statement attempts to divide Y by Z, but calls a routine named HandleZeroDivide
if an EZeroDivide exception is raised.
The syntax of a try...except statement is
try statements except exceptionBlock end
where statements is a sequence of statements (delimited by semicolons) and
exceptionBlock is either
• another sequence of statements or
• a sequence of exception handlers, optionally followed by
else statements
An exception handler has the form
on identifier: type do statement
where identifier: is optional (if included, identifier can be any valid identifier), type is a
type used to represent exceptions, and statement is any statement.
A try...except statement executes the statements in the initial statements list. If no
exceptions are raised, the exception block (exceptionBlock) is ignored and control
passes to the next part of the program.
If an exception is raised during execution of the initial statements list, either by a raise
statement in the statements list or by a procedure or function called from the
statements list, an attempt is made to “handle” the exception:
• If any of the handlers in the exception block matches the exception, control passes
to the first such handler. An exception handler “matches” an exception just in case
the type in the handler is the class of the exception or an ancestor of that class.
• If no such handler is found, control passes to the statement in the else clause, if
there is one.
• If the exception block is just a sequence of statements without any exception
handlers, control passes to the first statement in the list.
If none of the conditions above is satisfied, the search continues in the exception
block of the next-most-recently entered try...except statement that has not yet exited.
If no appropriate handler, else clause, or statement list is found there, the search
propagates to the next-most-recently entered try...except statement, and so forth. If
the outermost try...except statement is reached and the exception is still not handled,
the program terminates.