ABAP – Class based exceptions

SAPThere are several ways how to handle errors or warnings in ABAP and in this article I’ll try to present exceptions. Specifically – global class based exceptions in ABAP

  1. The most elegant way how to handle exception messages is to have them all stored at one place – ideally in a message class. So the first step will be message class creation (if you don’t already have one) in SE91.
    In this message class you can create your desired messages – you can use the most generic message

    & & & &

    but in our example we’ll use the following:

    Material & does not exist

    Messages definition

  2. Now we can step forward to create the exception class itself:
    In SE24 create new class of type “Exception” named i.e. ZCX_MY_EXCEPTION derived/inherited (in most cases) from CX_STATIC_CHECK and check the option “With Message Class”
    Exception class creation
  3. Note: Step 1 and checking option “With message class” in step 2 can be ommited and texts will be created and stored in the text management OTR. But it is not possible to combine both text variants in one exception class.
  4. Because we have parameters in our exception messages we have to define these parameters in our exception class. The most generic would be standard MSGV1 – MSGV4
    Exception class parameters
  5. Now we extend our exception by adding new specific exception IDs. To do that, go to Texts tab and create new exception ID, i.e. MATERIAL_NOT_FOUND and assign it with message class, message number and bind any message attributes (& in the message text) to the corresponding exception attributes.
    Exception class Exception IDs
  6. Note: If you don’t specify Exception ID when raising the exception then the default exception ID (it has the same name as exception class) is used and it’s text is generated.
  7. And that’s it!
    Now you can simply use your new exception class with specific exception IDs in your program like in the following code:

    DATA l_exc TYPE REF TO zcx_my_exception.
    
    TRY.
    * Exception thrown
      RAISE EXCEPTION TYPE zcx_my_exception
        EXPORTING
          textid = zcx_my_exception=>material_not_found
          msgv1  = '1234567'.                     "material number
    CATCH zcx_my_exception into l_exc.
      message l_exc type 'E'.
    endtry.

    Your MESSAGE is displayed automatically, with the attribute values inserted. There are no calls to get_text() or get_longtext(), and no data declarations for the resulting message string.
    Exception thrown

Leave a Reply