TRY and CATCH statements are used for handling the class bases exception handling in ABAP programs. TRY statement will open a control structure and it always end with ENDTRY statement. Here is the syntax
TRY
[Try block]
CATCH [BEFORE UNWIND] cx_class1 cx_class2 … [INTO oref].
[Catch block 1]
CATCH [BEFORE UNWIND] cx_class3 cx_class4 … [INTO oref2].
[Catch block 2]
.
.
CLEANUP.
[Cleanup block]
ENDTRY.
Now let us look into each of these blocks and its activities.
TRY block: It contains the application coding whose exceptions to be handles. If no exception found in this block, the control will go to ENDTRY and the program will continue its execution from there.
CATCH block: If any exception is occurs in TRY block, CATCH statement with the same exception will be executed. And CATCH block will contain the codlings for handling that execution. When an exception occurred, system search all the exception handlers in a specified order and the first CATCH block with the CATCH statement specifies the same exception class or its super classes will be executed.
Syntax
CATCH [BEFORE UNWIND] cx_class1 cx_class2 … [INTO oref].
See the details of additions specifies with CATCH statement
- BEFORE UNWIND: the context, in which the exception was raised, including all called procedures and their local data, is deleted only after exiting the CATCH block. If this addition is not specified, the context is deleted before the CATCH block is executed.
- INTO oref: This addition is sued for placing the exception object into a reference variable.
CLEANUP block: TRY ENDTRY control structure can have a nested structure. That means Inside one TRY control structure other TRY ENDTRY structures can be added like as follows.
TRY
..
..
TRY
..
TRY
..
..
ENDTRY
..
ENDTRY
ENDTRY.
In some scenarios exception occurring in one TRY block and the exception handler CATCH statement for that will be in another TRY block .So in that cases we need to maintain the application context for exception propagation. Here comes the importance of CLEANUP statement and CLEANUP block. If any exception in a TRY block occurs the CLEANUP block in the same TRY control structure will be executed. The CLEANUP block must be executed completely and must be left with ENDTRY so that the exception can be propagated to your handler. CLEANUP block will maintain the application context. We can also clean up the context of the TRY block in a CLEANUP block for bringing the objects into a consistent stage or release external resources.
CATCH statement is an option one, but it’s important to avoid issues in some scenarios.
Also Read : View Other ABAP Keywords & Syntax -> ABAP Transaction codes