Name

On Directive

Syntax

try
  Statements...
except
  on Variable: Class name do Statement;
  on Class name do Statement;
  else Statements...
end;

Description

The on directive introduces an exception handler in a try-except statement. You can have any number of exception handlers. Each one introduces an exception class, possibly with a variable name.

Delphi tests the exception object against each exception class, in order of appearance. The search stops with the first handler where the exception object’s class matches the handler’s class or is derived from the handler’s class (the is operator returns True). Delphi then executes the associated statement (or block), and if that statement does not raise another exception, execution continues with the statement following the end keyword for the try-except statement.

If the handler includes a variable name, Delphi assigns the exception object to that variable. The variable’s lexical scope is the exception handler, so you cannot refer to the variable in a different handler or outside the try-except statement.

If no classes match the exception object, and an else clause appears, Delphi executes the statements following the else. If no classes match, and the try-except has no else clause, the same exception is raised, giving another try-except statement an opportunity to handle the exception.

At the end of the exception handler, Delphi frees the exception object unless the handler raises the same exception with the plain raise statement.

Tips and Tricks ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.