When To Use Exceptions

Exceptions provide an elegant way to trap runtime errors without halting the program and without awkward conditional statements. The requirements imposed by exception handling semantics impose a code/data size and runtime performance penalty. 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:

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.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment