[ABAP] Objektorientiertes (OO) Exceptionhandling mit TRY … CATCH

Variante 1 (implizites Erzeugen von Objekten)

* DEMO_CATCH_EXCEPTION

START-OF-SELECTION.
  TRY.
      RAISE EXCEPTION TYPE cx_sy_zerodivide.
* Exception abfangen
    CATCH cx_sy_zerodivide INTO DATA(e_text).
      MESSAGE e_text->get_text( ) TYPE 'S' DISPLAY LIKE 'E'.
  ENDTRY.

Variante 2 (explizites Erzeugen von Objekten)

START-OF-SELECTION.
  TRY.
      DATA(excp) = NEW cx_os_object_not_found( classname = 'MYCLASS' ).
      RAISE EXCEPTION excp.
* Exception abfangen
    CATCH cx_os_object_not_found INTO DATA(e_text).
      MESSAGE e_text->get_text( ) TYPE 'S' DISPLAY LIKE 'E'.
  ENDTRY.

Variante 3 (explizites Erzeugen von Objekten – RE-RAISING)

START-OF-SELECTION.
  TRY.
      TRY.
          DATA(excp) = NEW cx_sy_file_open( filename = 'xyz.txt' ).
          RAISE EXCEPTION excp.
* Exception abfangen
        CATCH cx_root INTO DATA(exc).
* RE-RAISING einer neuen Exception
          RAISE EXCEPTION TYPE cx_sy_file_position
            EXPORTING
              previous = exc.
      ENDTRY.
* Exception abfangen
    CATCH cx_root INTO DATA(exc2).
      MESSAGE exc2->get_text( ) TYPE 'S' DISPLAY LIKE 'E'.
  ENDTRY.

Variante 4 (Runtime Exceptions)

START-OF-SELECTION.
  TRY.
* implizites Erzeugen von Exception cx_sy_zerodivide
      DATA(erg) = 1 / 0.
* Exception abfangen
    CATCH cx_root INTO DATA(e_text).
      MESSAGE e_text->get_text( ) TYPE 'S' DISPLAY LIKE 'E'.
  ENDTRY.

Variante 5 (Beispiel – Definition und Auslösen einer OO-Exception)

CLASS my_class DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS: my_method
* Exception propagieren
      RAISING cx_sy_zerodivide.
ENDCLASS.
 
CLASS my_class IMPLEMENTATION.
  METHOD my_method.
    ...
* Auslösen der Systemexception cx_sy_zerodivide
    RAISE EXCEPTION TYPE cx_sy_zerodivide.
    ...
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
* Behandlung einer OO-Exception
  TRY.
* Funktionsaufruf, der Exception cx_sy_zerodivide auslösen kann
      my_class=>my_method( ).
* Exception cx_sy_zerodivide abfangen
    CATCH cx_sy_zerodivide INTO DATA(e_text).
      MESSAGE e_text->get_text( ) TYPE 'S' DISPLAY LIKE 'E'.
  ENDTRY.

Weiterführende Information: Link und Link