Exception Handling in Constructor

Exception Handling in Constructor


Constructor can have Exception parameter which will be declared at the time of declaration and instantiate at the time of creating the object. Exception parameter will take a constant value and sy-subrc will return that constant value if the exception raises.

Here is a program which gives the output of Factorial value. The constructor method import the input parameter and has an exception parameter. In the method we declare the condition that if the input parameter is greater than 10 then exception will be raised otherwise the Factorial function will work. After the create object we check the value of sy-subrc and if exception raises then sy-subrc will return the constant value which is instantiated to exception parameter.

REPORT  zsr_test.

PARAMETERS p_data TYPE i.

*----------------------------------------------------------------------*
*       CLASS cl_construct DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_construct DEFINITION.
  PUBLIC SECTION.
    METHODS constructor IMPORTING  i_data TYPE i
                        EXCEPTIONS exc.
ENDCLASS.                    "cl_construct DEFINITION

*----------------------------------------------------------------------*
*       CLASS cl_construct IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_construct IMPLEMENTATION.
  METHOD constructor.
    IF i_data GT 10.
      RAISE exc.
    ELSE.
      WRITE: / i_data, ' is less than 10'.
    ENDIF.
  ENDMETHOD.                    "constructor
ENDCLASS.                    "cl_construct IMPLEMENTATION

START-OF-SELECTION.  DATA obj TYPE REF TO cl_construct.
  CREATE OBJECT obj EXPORTING i_data = p_data EXCEPTIONS exc = 1.

  IF sy-subrc <> 0.
    WRITE: / p_data, 'is greater than 10, so SY-SUBRC = ', sy-subrc.
  ENDIF.

Below is the Output:


Exception Raised:


Otherwise:


Share this

Related Posts