Exceptions | Previous Top Next

Exceptions provide an elegant way to trap runtime errors without halting the program and without awkward conditional statements. The complexity of Pascal's exception-handling mechanism, however, makes it inefficient, and it should therefore be used judiciously. While it is possible to raise exceptions for almost any reason, and to protect almost any block of code by wrapping it in a try...except or try...finally statement, in practice these tools are best reserved for special situations.
Exception handling is appropriate for errors whose chances of occurring are low or difficult to assess, but whose consequences are likely to be catastrophic (such as crashing the application); for error conditions that are complicated or difficult to test for in if...then statements; and when you need to respond to exceptions raised by the operating system or by routines whose source code you don't control. Exceptions are commonly used for hardware, memory, I/O, and operating-system errors.
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 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.