Quick start manual

Classes and objects
7-29
Exceptions
Raising and handling exceptions
To raise an exception object, use an instance of the exception class with a raise
statement. For example,
raise EMathError.Create;
In general, the form of a raise statement is
raise object at address
where object and at address are both optional; see “Re-raising exceptions” on
page 7-32. When an address is specified, it can be any expression that evaluates to a
pointer type, but is usually a pointer to a procedure or function. For example:
raise Exception.Create('Missing parameter') at @MyFunction;
Use this option to raise the exception from an earlier point in the stack than the one
where the error actually occurred.
When an exception is raised—that is, referenced in a raise statement—it is governed
by special exception-handling logic. A raise statement never returns control in the
normal way. Instead, it transfers control to the innermost exception handler that can
handle exceptions of the given class. (The innermost handler is the one whose
try...except block was most recently entered but has not yet exited.)
For example, the function below converts a string to an integer, raising an
ERangeError exception if the resulting value is outside a specified range.
function StrToIntRange(const S: string; Min, Max: Longint): Longint;
begin
Result := StrToInt(S); // StrToInt is declared in SysUtils
if (Result < Min) or (Result > Max) then
raise ERangeError.CreateFmt(
'%d is not within the valid range of %d..%d',
[Result, Min, Max]);
end;
Notice the CreateFmt method called in the raise statement. Exception and its
descendants have special constructors that provide alternative ways to create
exception messages and context IDs. See the online Help for details.
A raised exception is destroyed automatically after it is handled. Never attempt to
destroy a raised exception manually.
Note
Raising an exception in the initialization section of a unit may not produce the
intended result. Normal exception support comes from the SysUtils unit, which must
be initialized before such support is available. If an exception occurs during
initialization, all initialized units—including SysUtils—are finalized and the
exception is re-raised. Then the exception is caught and handled, usually by
interrupting the program. Similarly, raising an exception in the finalization section of
a unit may not lead to the intended result if SysUtils has already been finalized when
the exception has been raised.