Quick start manual
7-28
Delphi Language Guide
Exceptions
Conditional statements are often the best way to test for errors. For example, suppose
you want to make sure that a file exists before trying to open it. You could do it this
way:
try
AssignFile(F, FileName);
Reset(F); // raises an EInOutError exception if file is not found
except
on Exception do ...
end;
But you could also avoid the overhead of exception handling by using
if FileExists(FileName) then // returns False if file is not found; raises no exception
begin
AssignFile(F, FileName);
Reset(F);
end;
Assertions provide another way of testing a Boolean condition anywhere in your
source code. When an Assert statement fails, the program either halts with a runtime
error or (if it uses the SysUtils unit) raises an EAssertionFailed exception. Assertions
should be used only to test for conditions that you do not expect to occur. For more
information, see the online Help for the standard procedure Assert.
Declaring exception types
Exception types are declared just like other classes. In fact, it is possible to use an
instance of any class as an exception, but it is recommended that exceptions be
derived from the Exception class defined in SysUtils.
You can group exceptions into families using inheritance. For example, the following
declarations in SysUtils define a family of exception types for math errors.
type
EMathError = class(Exception);
EInvalidOp = class(EMathError);
EZeroDivide = class(EMathError);
EOverflow = class(EMathError);
EUnderflow = class(EMathError);
Given these declarations, you can define a single EMathError exception handler that
also handles EInvalidOp, EZeroDivide, EOverflow, and EUnderflow.
Exception classes sometimes define fields, methods, or properties that convey
additional information about the error. For example,
type EInOutError = class(Exception)
ErrorCode: Integer;
end;