OOPS ABAP: Exception class with Message class

 

Exception Class:

  • Exception is a problem that arises during the execution of the program.
  •  The purpose of exception class is to raise and handle the exceptions.
  •  We use TRY block to raise the exception and CATCH block to handle the exception.
  •  The exception class name must start with CX.
  •  CX_ROOT is the global class(Parent class) for all the exceptions.

Example:

Steps:

Create message class


  • Goto se24 and enter class name.(Eg: ZCX_STU).
  • Select radio button ' Exception class' and check the check box 'with messages of message classes as exception texts'.
  • Press enter. 

 

  • Enter LV_ID in attributes tab.

  • Click on 'message text' button.
  •  Enter Message class name,message number and attribute 'LV_ID' and click on 'change'.
 
  • Check and activate.
 
 
Using the above class in program.
 
*&---------------------------------------------------------------------*
*& Report ZVB_STU_EXC_CLS
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT zvb_stu_exc_cls.

*TABLES: zvb_stu.
PARAMETERS:p_id TYPE zvb_stu-zstu_id.

DATA:lv_id   TYPE zstu_id,
     lv_name TYPE zstu_name,
     lv_dep  TYPE zstu_dep.

DATA:lo_exception TYPE REF TO zcx_stu1,
     lv_msg       TYPE string.

AT SELECTION-SCREEN.
  TRY.
      IF p_id IS INITIAL.
        RAISE EXCEPTION TYPE zcx_stu1
          EXPORTING
            textid zcx_stu1=>zcx_mandt
*           previous =
          .
      ENDIF.

    CATCH zcx_stu1 INTO lo_exception.
      CALL METHOD lo_exception->if_message~get_text
        RECEIVING
          result lv_msg.
      MESSAGE lv_msg TYPE 'E'.

  ENDTRY.
  TRY.
      SELECT SINGLE zstu_id zstu_name zstu_dep
        FROM zvb_stu
        INTO lv_id,lv_name,lv_dep )
        WHERE zstu_id p_id.
      IF sy-subrc <> 0.
        RAISE EXCEPTION TYPE zcx_stu1
          EXPORTING
            textid zcx_stu1=>zcx_stu1
*           previous =
            lv_id p_id
          .
      ENDIF.

    CATCH zcx_stu1 INTO lo_exception.

      CALL METHOD lo_exception->if_message~get_text
        RECEIVING
          result lv_msg.
      MESSAGE lv_msg TYPE 'E'.
  ENDTRY.

  START-OF-SELECTION.
  WRITELV_ID,
        / LV_NAME,
        / LV_DEP.

Comments

Popular posts from this blog

Passing Dynamic Variables to SO10 TEXT

Implicit Enhancement with Example

TMG Events