8 | Error Handling with Exceptions
The details of the error report generated in the
CATCH
block in Listing 8.3 were
obtained via method calls made using the
1
r_ex object reference variable. The
lr_ex object reference variable is initialized using the optional
INTO
addition of
the
CATCH
statement
1
. Here, notice that the static type of the ir_ex object refer-
ence is compatible with the exception type
CX_SY_MOVE_CAST_ERROR.
As you can
see, an exception object can be used to obtain quite a bit of useful information
about the exception, including a short and long text description of the problem,
the line number in the program that triggered the exception, and so on.
You can include as many
CATCH
blocks as you want inside of
a TRY
statement. For
example, there might be certain types of exceptions that are raised from methods
of
class
lcl_parent or lcl_chtld. Whenever an exception is raised in a
TRY
state-
ment with multiple
CATCH
blocks, the system searches through the
CATCH
blocks to
find a suitable handler that can handle an exception of a given type. Sometimes,
it may be preferable to use a generic exception type in an exception handler block
to handle families of related exceptions. For example, rather than setting up a
specific exception handler block to handle exception types such as division by
zero and arithmetic overflow (which are defined in exception classes
CX_SY_ZERODIVIOE
and
CX_SY_ARITHMETIC_0VERF10W,
respectively), you could
define a
CATCH
block using the
CX_SY_ARITHMETIC_ERR0R
superclass. However, if
you use generic exception types in your
CATCH
blocks, they must be declared after
any
CATCH
blocks that define exception handlers for subordinate classes. If you
think about it, this makes sense as the more specific exception handlers would
never be reached because the system would first find a matching exception han-
dler for the superordinate class. If all of this seems confusing, don't worry, the
compiler will cell you where you've gone wrong.
A tendency of some developers new to the class-based exception handling con-
cept is to create extremely large
TRY
statements that surround their entire pro-
gram logic. This is a very poor design practice that minimizes the effectiveness of
the exception handlers. A good rule of thumb is to create
TRY
statements that
encapsulate a single logical unit of work. Therefore, ifyou find that you are mix-
ing and matching many different types of exception classes in
CATCH
blocks, it is
likely that your
TRY
statement is too large. Smaller
TRY
statements are much easier
to follow and trace.
1 If
the
INTO
addition of
the
CATCH
statement is not used, an exception object will not be generated
to conserve system resources.
208