Class-Based Exceptions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Programs meet situations in which they cannot go on in a sensible way: a number is divided by zero, an amount is negative,
a file is missing. ABAP calls such a situation an exception. The program that finds the problem raises the exception, and
a program further up the call chain can catch it and decide what to do, for example show a message and ask for a new
value, instead of stopping. A newcomer meets exceptions the first time a program ends with a red error screen, and every
method that can fail reports its failure through one. After reading this page you can read and write a TRY block, tell
the three kinds of exception apart, define an exception class of your own, give it a readable text, and understand why
an exception that nobody catches ends in a runtime error. The page is written against Standard ABAP release 8.16 and ABAP
for Cloud Development release 9.20 (2608). Class-based exceptions are part of the core language and work the same in
ABAP Cloud, in classic Standard ABAP, on premise and in the Public Edition. The older exception mechanisms in the last
sections, CATCH SYSTEM-EXCEPTIONS and the EXCEPTIONS list of function modules and methods, are classic Standard ABAP
only and are shown so that you can read old code.
Before you read
-
Programming Concepts for Newcomers: what a class, an object and a method are.
-
Control Flow: blocks of statements, loops and conditions.
-
Data Types and Data Objects: declaring data and using inline declarations such as
DATA(name). -
Messages: message classes, which can supply the text of an exception.
Key terms
-
Exception: an event during the run of a program that interrupts the normal flow because the program cannot continue in a meaningful way.
-
Exception class: a class whose objects describe an exception; its name starts with
CX_for SAP classes andZCX_for your own. -
Exception category: one of three groups, static check, dynamic check and no check, that decides whether the caller must declare or handle an exception.
-
Catchable exception: an exception that a program can handle with
TRYandCATCH; the opposite is an uncatchable one, which ends the program. -
Runtime error: the termination of a program that raised an exception nobody handled, recorded in a short dump.
-
Short dump: the error log that ABAP writes for a runtime error, read with the ABAP dump analysis tool, transaction ST22.
What happens when something goes wrong
An exception is raised in one of two ways. The ABAP runtime raises it for a situation it detects itself, for example the
division of a number by zero. Your program raises it with the statement RAISE EXCEPTION when a check fails, for example
a claim amount that is not greater than zero. Raising stops the statement block that is running and starts a search: ABAP
looks for a CATCH block that handles this kind of exception first in the surrounding TRY block, then in the caller of
the method, then in the caller of the caller, and so on up the call chain.
If a handler is found, its statements run and the program continues after the ENDTRY of that handler. If no handler
is found, the exception is not caught: the program ends with a runtime error and a short dump, and the database changes of
the current work unit are rolled back. The Keyword Documentation calls the exceptions you can catch catchable and the
others uncatchable; every catchable exception is a class-based exception, an object of an exception class. This is the
only kind of exception that new code defines. The sections about CATCH SYSTEM-EXCEPTIONS and the EXCEPTIONS list below
describe the predecessors that you only meet in old programs.
The three exception categories
Every exception class is a direct or indirect subclass of one of three abstract classes, and all three are subclasses of
the root class CX_ROOT. The one you pick decides how strictly ABAP makes the caller deal with the exception.
| Category | What the caller must do | Use it for |
|---|---|---|
|
Handle the exception with |
Errors that a caller can reasonably react to, such as an invalid input from a user. This is the usual choice for your own classes. |
|
The exception must also be handled or declared, but this is checked only at run time, at the moment the exception leaves a method that did not declare it. |
Errors that a check before the call would have avoided, such as a division by zero, which a test for zero prevents. |
|
Nothing. The exception is implicitly declared in every method signature and can always propagate. |
Errors that can occur anywhere and that no caller can fix, such as running out of memory. |
If an exception of the static or the dynamic category leaves a method without being declared in its signature, ABAP raises
the predefined exception CX_SY_NO_HANDLER at the place of the call, and the original exception is kept in its attribute
previous. In the diagram, CX_UUID_ERROR is a predefined static exception, CX_SY_ZERODIVIDE a predefined dynamic one
that comes from CX_SY_ARITHMETIC_ERROR, and ZCX_EXP_INVALID_AMOUNT is the class that this page builds.
Raising an exception
The statement RAISE EXCEPTION raises a class-based exception. The usual form creates the exception object in place with
the NEW operator and passes values for the constructor:
RAISE EXCEPTION NEW zcx_exp_invalid_amount( amount = amount ).
The older form RAISE EXCEPTION TYPE zcx_exp_invalid_amount EXPORTING amount = amount. does the same and is still
common in existing code. You can also raise an object that you created before, or an exception that you caught earlier,
with RAISE EXCEPTION oref. Inside a COND or SWITCH expression the addition THROW raises an exception in the
place of an operand. Only exception classes that are not abstract can be created, so you cannot raise CX_STATIC_CHECK or
CX_ROOT themselves.
A method that can raise a static-check exception says so in its signature with RAISING. The caller then knows what to
expect without reading the body.
Catching exceptions with TRY
The block between TRY. and ENDTRY. is a protected area. When an exception is raised in it, ABAP leaves the block and
runs the first CATCH block whose class matches the exception. A CATCH for a class also matches every subclass of it, so
a handler for CX_SY_ARITHMETIC_ERROR catches a division by zero, which belongs to the subclass CX_SY_ZERODIVIDE. Put the
specific classes first and a general class last, because the first matching block is the one that runs.
-
CATCH cx_a cx_b INTO DATA(error).handles several classes in one block and stores the exception object inerror. WithoutINTOyou can still react, but you cannot read the text or the attributes. -
A handler for
CX_ROOTcatches everything catchable. It hides which errors to expect, so name the specific classes. -
After a
CATCHblock ends, the program continues afterENDTRY. If no block matches, the exception travels to the caller.
Every exception object offers get_text, which returns the exception text, and get_source_position, which returns the
program, the include and the line of the statement that raised it. The attributes textid, previous and is_resumable
are available as well; previous and is_resumable appear below.
Source: ABAP Keyword Documentation: TRY
Example: an exception class for the Expense claims application
The Expense claims application checks the amount of every claim item. The class zcx_exp_invalid_amount is a static-check
exception that carries the offending amount, and it builds a readable text from it. The text is produced by redefining
get_text, which keeps this example free of a message class.
CLASS zcx_exp_invalid_amount DEFINITION
PUBLIC
INHERITING FROM cx_static_check
FINAL
CREATE PUBLIC.
PUBLIC SECTION.
DATA amount TYPE decfloat34 READ-ONLY.
METHODS constructor
IMPORTING amount TYPE decfloat34
previous LIKE previous OPTIONAL.
METHODS if_message~get_text REDEFINITION.
ENDCLASS.
CLASS zcx_exp_invalid_amount IMPLEMENTATION.
METHOD constructor ##ADT_SUPPRESS_GENERATION.
super->constructor( previous = previous ).
me->amount = amount.
ENDMETHOD.
METHOD if_message~get_text.
result = |Invalid claim amount { amount DECIMALS = 2 }: it must be greater than zero|.
ENDMETHOD.
ENDCLASS.
The class check below raises it. Its method declares the exception with RAISING, so every caller has to handle it or
declare it too. The second method has no RAISING; it only exists to produce a runtime exception for the third part of
the report.
CLASS zcl_exp_claim_check DEFINITION
PUBLIC
FINAL
CREATE PUBLIC.
PUBLIC SECTION.
CLASS-METHODS check_amount
IMPORTING amount TYPE decfloat34
RAISING zcx_exp_invalid_amount.
CLASS-METHODS ratio
IMPORTING part TYPE i
total TYPE i
RETURNING VALUE(ratio) TYPE i.
ENDCLASS.
CLASS zcl_exp_claim_check IMPLEMENTATION.
METHOD check_amount.
IF amount <= 0.
RAISE EXCEPTION NEW zcx_exp_invalid_amount( amount = amount ).
ENDIF.
ENDMETHOD.
METHOD ratio.
ratio = part * 100 / total.
ENDMETHOD.
ENDCLASS.
The report runs three cases. The first raises the custom exception and reads its text and its attribute, the second passes a valid amount, and the third catches a runtime exception through its superclass.
REPORT zp_exc.
START-OF-SELECTION.
" 1. a checked exception that the caller must handle or declare
TRY.
zcl_exp_claim_check=>check_amount( CONV #( '-5.00' ) ).
WRITE / 'amount accepted'.
CATCH zcx_exp_invalid_amount INTO DATA(invalid).
WRITE / invalid->get_text( ).
WRITE / |amount kept in the object: { invalid->amount DECIMALS = 2 }|.
ENDTRY.
" 2. a valid amount passes
TRY.
zcl_exp_claim_check=>check_amount( CONV #( '12.50' ) ).
WRITE / 'amount accepted'.
CATCH zcx_exp_invalid_amount.
WRITE / 'rejected'.
ENDTRY.
" 3. a predefined exception raised by the runtime, caught through its superclass
TRY.
DATA(percent) = zcl_exp_claim_check=>ratio( part = 5 total = 0 ).
WRITE / |percent: { percent }|.
CATCH cx_sy_arithmetic_error INTO DATA(arith).
WRITE / |caught { cl_abap_typedescr=>describe_by_object_ref( arith )->get_relative_name( ) }|.
ENDTRY.
Source: ABAP Keyword Documentation: TRY
This example runs in the local playground, which is a community tool and not SAP software, and prints the following. The playground treats the report and the two classes as ordinary source files, so the listings run as written.
Invalid claim amount -5.00: it must be greater than zero amount kept in the object: -5.00 amount accepted caught CX_SY_ZERODIVIDE
The third line shows that a valid amount passes without any exception, and the fourth shows that a handler for
CX_SY_ARITHMETIC_ERROR caught the zero division and that the object is an instance of the subclass CX_SY_ZERODIVIDE.
Exception texts
Every exception has a text that describes the problem. If the exception is caught, you read it with get_text. If it is not
caught, the text appears in the short dump. The text of an exception class is chosen by its textid: each text is a constant
in the public section of the class, the constructor has an input parameter textid, and when you do not pass one the
predefined text with the same name as the class is used. In a global class these texts usually refer to messages of a message
class, so translators and the message maintenance tool handle them like any other message; see
Messages.
A class can get the message handling for free by implementing one of two system interfaces. IF_T100_MESSAGE assigns a
message to each text constant. IF_T100_DYN_MSG includes IF_T100_MESSAGE and is the more flexible one: it lets you attach
any message when you raise the exception, with the additions MESSAGE and WITH of RAISE EXCEPTION. When you create a
global exception class in ADT and name its superclass, the wizard generates the constructor that these interfaces need. The
following sketch uses the second interface and a message class ZEXP with message 001 ("Claim &1 has an invalid amount").
It requires an SAP system, because the message class has to exist in the system; not run here.
CLASS zcx_exp_claim_error DEFINITION
PUBLIC
INHERITING FROM cx_static_check
FINAL
CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES if_t100_dyn_msg.
ENDCLASS.
" in the code that raises it
RAISE EXCEPTION TYPE zcx_exp_claim_error
MESSAGE e001(zexp) WITH claim_id.
Passing the original cause on with PREVIOUS
A method often catches a low-level exception and raises a higher-level one that makes sense to its caller. The constructor
of every exception class has an optional parameter previous, and passing the caught exception there keeps the original
cause. A reader of the final exception can follow the chain through the attribute previous. The class
zcx_exp_invalid_amount above declares that parameter for this reason.
CLEANUP, RETRY and RESUME
Three statements control what happens around the handler.
-
CLEANUPstarts a block of aTRYstructure that runs when an exception raised inside thatTRYblock is handled further out, by theCATCHof an outerTRY. It is the place to put an object back in a consistent state or release a resource, because the outer handler can no longer reach what the inner block owned. ACLEANUPblock must run to its end and cannot be left withRETURN, and any exception raised in it must be handled in it. It does not run when the sameTRYstructure handles the exception. -
RETRYis allowed only in aCATCHblock. It leaves the handler and runs the wholeTRYblock again. Remove the cause of the exception before the retry, or the program loops forever. -
RESUMEis allowed only in aCATCH BEFORE UNWINDblock, and only for a resumable exception. It leaves the handler and continues after the statement that raised the exception. The exception must have been raised withRAISE RESUMABLE EXCEPTION, and every method it passed through must have declared itRESUMABLE; an exception of the categoryCX_NO_CHECKcounts as declared everywhere. The attributeis_resumabletells the handler whether resuming is possible. Resuming does not runCLEANUPblocks.
The next report runs a CLEANUP block in an inner method and a chain with previous. It runs in the local playground.
REPORT zp_exc2.
CLASS lcx_demo DEFINITION INHERITING FROM cx_no_check.
ENDCLASS.
CLASS lcx_demo IMPLEMENTATION.
ENDCLASS.
CLASS lcl_demo DEFINITION.
PUBLIC SECTION.
CLASS-METHODS inner.
CLASS-METHODS outer.
CLASS-METHODS wrapped.
ENDCLASS.
CLASS lcl_demo IMPLEMENTATION.
METHOD inner.
TRY.
RAISE EXCEPTION NEW lcx_demo( ).
CLEANUP.
WRITE / 'cleanup in inner'.
ENDTRY.
ENDMETHOD.
METHOD outer.
TRY.
inner( ).
CATCH lcx_demo.
WRITE / 'handled in outer'.
ENDTRY.
ENDMETHOD.
METHOD wrapped.
TRY.
TRY.
DATA(zero) = 0.
DATA(r) = 1 / zero.
CATCH cx_sy_zerodivide INTO DATA(low).
RAISE EXCEPTION NEW lcx_demo( previous = low ).
ENDTRY.
CATCH lcx_demo INTO DATA(high).
WRITE / |previous kept: { xsdbool( high->previous IS BOUND ) }|.
ENDTRY.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
" CLEANUP runs when the exception is handled by an outer TRY
lcl_demo=>outer( ).
" PREVIOUS chains the original exception
lcl_demo=>wrapped( ).
The output shows that the cleanup ran before the outer handler, and that the new exception still holds the original one
(X is the value of the true flag).
cleanup in inner handled in outer previous kept: X
The playground does not support RETRY and its exception class lacks is_resumable, so the next listing requires an SAP
system; not run here. It first resumes after a resumable warning and then retries a division after removing its cause.
REPORT zp_exc3.
CLASS lcx_low_stock DEFINITION INHERITING FROM cx_no_check.
ENDCLASS.
CLASS lcx_low_stock IMPLEMENTATION.
ENDCLASS.
CLASS lcl_loader DEFINITION.
PUBLIC SECTION.
CLASS-METHODS load.
ENDCLASS.
CLASS lcl_loader IMPLEMENTATION.
METHOD load.
WRITE / 'before warning'.
RAISE RESUMABLE EXCEPTION NEW lcx_low_stock( ).
WRITE / 'after warning'.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
TRY.
lcl_loader=>load( ).
CATCH BEFORE UNWIND lcx_low_stock INTO DATA(warning).
IF warning->is_resumable = abap_true.
RESUME.
ENDIF.
ENDTRY.
DATA(divisor) = 0.
TRY.
DATA(result) = 100 / divisor.
CATCH cx_sy_zerodivide.
divisor = 4.
RETRY.
ENDTRY.
With a real system the first block writes before warning and after warning, because the handler resumes where the
exception was raised, and the second block runs the division twice and ends with a result of 25. That output is what the
documentation of RESUME and RETRY describes; it was not produced here.
Runtime errors and the dump analysis
A runtime error ends the program. It happens when a catchable exception is not handled, when the runtime raises an
uncatchable exception, when the program asks for it with RAISE SHORTDUMP or THROW SHORTDUMP, and when an ASSERT
statement finds its condition false. Every runtime error has a name, rolls back the database changes of the current work
unit and writes a short dump. For example, an unhandled division by zero of integers ends with the runtime error
COMPUTE_INT_ZERODIVIDE, and an unhandled exception of your own class ends with UNCAUGHT_EXCEPTION.
The short dump records what the program was doing: the runtime error name, the exception class, the program, the line and the
exception text. You read it in the ABAP dump analysis tool, which classic systems start with transaction ST22 in SAP GUI.
In ADT, the runtime errors caused by your own runs appear in a popup after a failed run and in the Feed Reader. A dump
is the correct end for a situation that cannot be handled, such as a failed ASSERT. For an error that a caller can react
to, raise a class-based exception instead, so that the caller decides.
Older material you may meet
Older books and programs know no exception classes. Two older mechanisms are still found in code that works today. Both belong to classic Standard ABAP; do not use them in new code.
CATCH SYSTEM-EXCEPTIONS catches runtime errors, that is the failures that the runtime itself detects, without any class.
The statement is marked obsolete in the Keyword Documentation. The block between CATCH SYSTEM-EXCEPTIONS and ENDCATCH
stops at the first runtime error that is listed, the program continues after ENDCATCH, and the number you assigned to the
error or the error group is in sy-subrc. The same code with TRY is shorter and works across method calls, which this
statement does not, because it can only catch errors inside one processing block. It requires an SAP system; not run here.
" obsolete: catch the group of arithmetic errors
DATA divisor TYPE i.
DATA result TYPE i.
CATCH SYSTEM-EXCEPTIONS arithmetic_errors = 4 OTHERS = 8.
result = 100 / divisor.
ENDCATCH.
IF sy-subrc <> 0.
WRITE / 'arithmetic error'.
ENDIF.
" replaced by
TRY.
result = 100 / divisor.
CATCH cx_sy_arithmetic_error.
WRITE / 'arithmetic error'.
ENDTRY.
Classic exceptions are the names listed after EXCEPTIONS in the interface of a function module or a method. The called
code raises one with RAISE name, the caller lists the names with numbers in the call, and after the call it tests
sy-subrc. Nothing says which exception happened except that number, no text and no data travel with it, and a caller that
forgets to test sy-subrc goes on as if nothing had happened. A new method uses RAISING with an exception class instead.
You still meet the classic form in many function modules, which were written before exception classes existed. It
requires an SAP system; not run here.
" classic: the called code raises not_found, the caller tests sy-subrc
CALL FUNCTION 'Z_EXP_READ_CLAIM'
EXPORTING
claim_id = claim_id
EXCEPTIONS
not_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
" no text, no data: only the number of the exception
ENDIF.
Rules of thumb
-
Define an exception class for every kind of error a caller may want to treat differently, and name it
ZCX_...in your namespace. -
Inherit from
CX_STATIC_CHECKfor errors a caller can fix, fromCX_DYNAMIC_CHECKfor errors a check beforehand avoids, and fromCX_NO_CHECKfor errors nobody can fix locally. -
Catch the specific class you expect, and catch
CX_ROOTonly at the outermost layer of a program. -
Keep
CLEANUPblocks short and free of anything that can fail. -
Put the cause in the exception, as attributes or through
previous, so that the handler can act on it.
Summary
-
An exception interrupts the program flow; a class-based exception is an object of a class under
CX_ROOT, raised withRAISE EXCEPTIONand handled withTRYandCATCH. -
The three categories decide how much the caller must do: handle or declare for
CX_STATIC_CHECKandCX_DYNAMIC_CHECK, with a syntax warning only for the first, and nothing forCX_NO_CHECK. -
A
CATCHblock matches the named class and its subclasses;INTOstores the object so that you can readget_textand its attributes. -
CLEANUP,RETRYandRESUMEcontrol what happens around a handler, andpreviouskeeps the original cause. -
An exception that nobody catches ends in a runtime error and a short dump, which you read in ST22 or in ADT.
-
CATCH SYSTEM-EXCEPTIONSand theEXCEPTIONSlist of function modules are older and classic only; read them in old code and use classes in new code.
Try it
To do this by hand, follow the guide Classes, Interfaces and Exceptions: it builds a claim validator class, a payout interface and an exception class.