RAD Studio |  |

Handling Classes of Exceptions
See Also
Collapse All

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:

Copy Code

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

Copy Code

    try
    {
      // statements that perform integer math operations
    }
    catch (EIntError &E)
    {
      // special handling for integer math errors
    }

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:

Copy Code

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

Copy Code

    try
    {
      // statements performing integer math
    }
    catch (const ERangeError &rangeErr)
    {
      // out-of-range handling
    }
    catch (const EIntError &intErr)
    {
      // handling for other integer math errors
    }

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

See Also

Exception-handling Statements

Scope of Exception Handlers

Reraising Exceptions

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!