Quick start manual
Classes and objects
7-33
Nested exceptions
Code executed in an exception handler can itself raise and handle exceptions. As long
as these exceptions are also handled within the exception handler, they do not affect
the original exception. However, once an exception raised in an exception handler
propagates beyond that handler, the original exception is lost. This is illustrated by
the Tan function below.
type
ETrigError = class(EMathError);
function Tan(X: Extended): Extended;
begin
try
Result := Sin(X) / Cos(X);
except
on EMathError do
raise ETrigError.Create('Invalid argument to Tan');
end;
end;
If an EMathError exception occurs during execution of Tan, the exception handler
raises an ETrigError. Since Tan does not provide a handler for ETrigError, the
exception propagates beyond the original exception handler, causing the EMathError
exception to be destroyed. To the caller, it appears as if the Tan function has raised an
ETrigError exception.
Try...finally statements
Sometimes you want to ensure that specific parts of an operation are completed,
whether or not the operation is interrupted by an exception. For example, when a
routine acquires control of a resource, it is often important that the resource be
released, regardless of whether the routine terminates normally. In these situations,
you can use a try...finally statement.
The following example shows how code that opens and processes a file can ensure
that the file is ultimately closed, even if an error occurs during execution.
Reset(F);
try
ƒ // process file F
finally
CloseFile(F);
end;
The syntax of a try...finally statement is
try statementList
1
finally statementList
2
end