Handling Classes of Exceptions

From RAD Studio
Jump to: navigation, search

Go Up to Writing Exception Handlers


Exceptions are always represented by classes. As such, you usually work with a hierarchy of exception classes. For example, VCL defines the ERangeError exception as a descendant of EIntError.

When you provide an exception handler for a base exception class, it catches not only direct instances of that class, but instances of any of its descendants as well. For example, the following exception handler handles all integer math exceptions, including ERangeError, EDivByZero, and EIntOverflow:

 try
 { statements that perform integer math operations }
 except
   on EIntError do { special handling for integer math errors };
 end;

You can combine error handlers for the base class with specific handlers for more specific (derived) exceptions. You do this by placing the catch statements in the order that you want them to be searched when an exception is thrown. For example, this block provides special handling for range errors, and other handling for all other integer math errors:

 try
 { statements performing integer math }
 except
   on ERangeError do { out-of-range handling };
   on EIntError do { handling for other integer math errors };
 end;

Note that if the handler for EIntError came before the handler for ERangeError, execution would never reach the specific handler for ERangeError.

See Also