ABAP includes various control statements that influence the program flow. One of these is RETURN, whose effect I recently misunderstood in a method. Below is a nonsensical example to illustrate the issue.
CLASS zcl_mke_test DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
METHODS constructor.
PROTECTED SECTION.
METHODS do_something RAISING cx_abap_invalid_value.
ENDCLASS.
CLASS zcl_mke_test IMPLEMENTATION.
METHOD constructor.
ENDMETHOD.
METHOD if_oo_adt_classrun~main.
TRY.
do_something( ).
CATCH cx_abap_invalid_value.
" exception handling
ENDTRY.
ENDMETHOD.
METHOD do_something.
" [..]
DO 5 TIMES.
IF sy-index = 4.
RETURN.
ENDIF.
ENDDO.
" [..]
RAISE EXCEPTION NEW cx_abap_invalid_value( ).
ENDMETHOD.
ENDCLASS.
I expected the RETURN statement within the loop to behave like an EXIT statement. That is, to leave the loop and then execute the instructions after ENDDO, possibly eventually reaching RAISE EXCEPTION.
Unfortunately, I was mistaken. RETURN at this point exits the method, not the loop. This behavior can be found in the official SAP documentation. Learned something new.
