In Java, the finally keyword is used to execute code (used with exceptions - try..catch statements) no matter if an exception is thrown or not (source).
For example:
try {
// this code might throw an exception
riskyCall();
// this code will only run if no exception was thrown above
mainProgram();
}
finally {
// this code will always run
cleanUp();
}
Is there an equivalent feature in ABAP? If not, what's an idiomatic way to implement the same functionality?
I know ABAP has a CLEANUP keyword, but this seems to only execute if an exception was thrown.
I experimented and found the following as a possible solution. Unfortunately, I can't think of any solution without code duplication.
METHOD risky_method.
TRY.
WRITE 'code before...'.
IF lv_error_condition = abap_true.
RAISE EXCEPTION TYPE cx_foo.
ENDIF.
WRITE 'Main program...'.
WRITE 'Cleanup...'.
CLEANUP.
WRITE 'Cleanup...'.
ENDTRY.
ENDMETHOD.
METHOD outer_scope.
TRY.
risky_method( ).
CATCH cx_foo INTO DATA(lx_foo).
WRITE 'Caught the error!'.
ENDTRY.
ENDMETHOD.
For the case where lv_error_condition equals abap_false, the output of executing method outer_scope is:
code before... Main program... Cleanup...
For the case where lv_error_condition equals abap_true, the output is:
code before... Cleanup... Caught the error!
This solution has the advantage that the cleanup always runs. It has the disadvantage that some code duplication is required, as the cleanup needs to be written twice. If the cleanup is packaged into a method then it's not a terrible amount of code duplication. :-/