banner ads

Exception Handling by Method

Method can raise exception like Function Modules. It depends on the value of sy-subrc. It is called after calling the method and with the help of that we can generate messages as required.

In the following program we have a selection screen parameter where we are giving values. Based on that value the sy-subrc will be modified. We have a method m_one where we have cases of sy-subrc. Now based on the value of sy-subrc the program will raise an exception. We generate message for this raised exception. The following program is actually a way to raise exceptions based on the sy-subrc value. In real time we don’t insert sy-subrc values manually. It is created as per the function of system variables.

REPORT  zsr_test NO STANDARD PAGE HEADING.

PARAMETERS p_subrc TYPE sy-subrc.

*----------------------------------------------------------------------*
*       CLASS cl_one DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_one DEFINITION.
  PUBLIC SECTION.
    METHODS m_one EXCEPTIONS e1 e2 e3 e4.
ENDCLASS.                    "cl_one DEFINITION

*----------------------------------------------------------------------*
*       CLASS cl_one IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_one IMPLEMENTATION.
  METHOD m_one.
    IF p_subrc IS NOT INITIAL.
      sy-subrc = p_subrc.
      CASE sy-subrc.
        WHEN '1'.
          MESSAGE 'Exception when sy-subrc = 1' TYPE 'I' RAISING e1.
        WHEN '2'.
          MESSAGE 'Exception when sy-subrc = 2' TYPE 'I' RAISING e2.
        WHEN '3'.
          MESSAGE 'Exception when sy-subrc = 3' TYPE 'I' RAISING e3.
        WHEN '4'.
          MESSAGE 'Exception when sy-subrc = 4' TYPE 'I' RAISING e4.
      ENDCASE.
    ENDIF.
  ENDMETHOD.                    "m_one
ENDCLASS.                    "cl_one IMPLEMENTATION

START-OF-SELECTION.  DATA obj TYPE REF TO cl_one.
  CREATE OBJECT obj.
  CALL METHOD obj->m_one
    EXCEPTIONS
      e1 = 1
      e2 = 2
      e3 = 3
      e4 = 4.

  IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
  ELSE.
    WRITE: / 'No Exception'.
  ENDIF.

At selection screen we are giving the value 1 and we get the following information message output.



Now by pressing the Enter the system gets back to the selection page. Now we are giving 3 and it generates the following message.

No comments