An exception is a problem that arises during the execution of a program. When an exception occurs the normal flow of the program is disrupted and the program application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
Exceptions provide a way to transfer control from one part of a program to another. ABAP exception handling is built upon three keywords − RAISE, TRY, CATCH and CLEANUP. Assuming a block will raise an exception, a method catches an exception using a combination of the TRY and CATCH keywords. A TRY - CATCH block is placed around the code that might generate an exception. Following is the syntax for using TRY – CATCH −
TRY.
Try Block <Code that raises an exception>
CATCH
Catch Block <exception handler M>
. . .
. . .
. . .
CATCH
Catch Block <exception handler R>
CLEANUP.
Cleanup block <to restore consistent state>
ENDTRY.
Exceptions can be raised at any point in a method, a function module, a subroutine, and so on. There are two ways an exception can be raised −
Raise and create an exception object simultaneously. Raise an exception with an exception object that already exists in the first scenario. The syntax is: RAISE EXCEPTION exep.
Handlers are used to catch exceptions.
Let’s take a look at a code snippet −
DATA: result TYPE P LENGTH 8 DECIMALS 2,
exref TYPE REF TO CX_ROOT,
msgtxt TYPE STRING.
PARAMETERS: Num1 TYPE I, Num2 TYPE I.
TRY.
result = Num1 / Num2.
CATCH CX_SY_ZERODIVIDE INTO exref.
msgtxt = exref→GET_TEXT( ).
CATCH CX_SY_CONVERSION_NO_NUMBER INTO exref.
msgtxt = exref→GET_TEXT( ).
In the above code snippet, we are trying to divide Num1 by Num2 to get the result in a float type variable.
Two types of exceptions could be generated.
Here are the five attributes and methods of exceptions −
REPORT ZExceptionsDemo.
PARAMETERS Num_1 TYPE I.
DATA res_1 TYPE P DECIMALS 2.
DATA orf_1 TYPE REF TO CX_ROOT.
DATA txt_1 TYPE STRING.
start-of-selection.
Write: / 'Square Root and Division with:', Num_1.
write: /.
TRY.
IF ABS( Num_1 ) > 150.
RAISE EXCEPTION TYPE CX_DEMO_ABS_TOO_LARGE.
ENDIF.
TRY.
res_1 = SQRT( Num_1 ).
Write: / 'Result of square root:', res_1.
res_1 = 1 / Num_1.
Write: / 'Result of division:', res_1.
CATCH CX_SY_ZERODIVIDE INTO orf_1.
txt_1 = orf_1→GET_TEXT( ).
CLEANUP.
CLEAR res_1.
ENDTRY.
CATCH CX_SY_ARITHMETIC_ERROR INTO orf_1.
txt_1 = orf_1→GET_TEXT( ).
CATCH CX_ROOT INTO orf_1.
txt_1 = orf_1→GET_TEXT( ).
ENDTRY.
IF NOT txt_1 IS INITIAL.
Write / txt_1.
ENDIF.
Write: / 'Final Result is:', res_1.
In this example, if the number is greater than 150, the exception CX_DEMO_ABS_TOO_LARGE is raised. The above code produces the following output for the number 160.
Square Root and Division with: 160
The absolute value of number is too high
Final Result is: 0.00
73 videos|68 docs
|
|
Explore Courses for Software Development exam
|