exceptiontry-catchabap

ABAP: how to catch `MESSAGE RAISING` type exception


Given a classic ABAP exception like the following:

MESSAGE ID 'XYZ' TYPE 'E' NUMBER 123 RAISING exception_name

How do I catch this exception in the calling code?

I have tried try/catch, CASE sy-subrc, and CATCH SYSTEM-EXCEPTIONS (this no longer even compiles as it's obsolete), but none of them work. The program just exits immediately and displays the error message at the bottom left of SAPGUI.


Solution

  • The solution is stated in the ABAP documentation of MESSAGE, RAISING:

    If the MESSAGE statement is executed with the addition RAISING during processing of a method or a function module whose caller assigns a return value to the exception exception using the addition EXCEPTIONS of the statement CALL, the statement has the same effect as the statement RAISE.

    In the exception link, you can see the handling chapter:

    The handling of non-class-based exceptions is made possible by the addition EXCEPTIONS in method calls and function module calls by assigning numeric values to the exceptions, which are used to fill the system field sy-subrc when the exception is raised. The actual error handling takes place after the call, when sy-subrc is evaluated.

    If the exception is raised inside a function module (or a subroutine inside this function module), you'd handle it this way:

    CALL FUNCTION '...'
      EXCEPTIONS
        exception_name = 1.
    IF sy-subrc = 1.
      " handling of exception_name
    ENDIF.
    

    If the exception is raised inside a method, you'd handle it this way:

    cl_foo=>bar( EXCEPTIONS exception_name = 1 ).
    IF sy-subrc = 1.
      " handling of exception_name
    ENDIF.
    

    The special exception name OTHERS may be used to not mention all exception names.

    Note that these "non-class-based exceptions" are obsolete, they "should not be defined any more in new developments." Instead you should use class-based exceptions (which work differently).

    References to the ABAP documentation for all non-class-based exception topics: