文章目录
- 1、自定义异常类
- 1、定义消息类
- 2、自定义异常类
- 2、调用
- 3、测试
- 总结
ABAP预定义的异常类在某些时候并不能精确地描述异常,此时就需要自定义异常类。
1、自定义异常类
1、定义消息类
2、自定义异常类
在Local Types中自定义异常类,当异常触发时,提示airline和connection不存在。
CLASS lcx_no_connection DEFINITION INHERITING FROM cx_static_check.
PUBLIC SECTION.
INTERFACES if_t100_message.
METHODS constructor
IMPORTING
textid LIKE if_t100_message=>t100key OPTIONAL
previous LIKE previous OPTIONAL
airlineid TYPE /dmo/carrier_id OPTIONAL
connectionnumber TYPE /dmo/connection_id OPTIONAL.
CONSTANTS:
BEGIN OF lcx_no_connection,
msgid TYPE symsgid VALUE 'ZMSG_KDLK',
msgno TYPE symsgno VALUE '000',
attr1 TYPE scx_attrname VALUE 'airlineid',
attr2 TYPE scx_attrname VALUE 'connectionnumber',
attr3 TYPE scx_attrname VALUE 'attr3',
attr4 TYPE scx_attrname VALUE 'attr4',
END OF lcx_no_connection.
DATA airlineid TYPE /dmo/carrier_id READ-ONLY.
DATA connectionnumber TYPE /dmo/connection_id READ-ONLY.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS lcx_no_connection IMPLEMENTATION.
METHOD constructor.
super->constructor( previous = previous ).
me->airlineid = airlineid.
me->connectionnumber = connectionnumber.
CLEAR me->textid.
IF textid IS INITIAL.
if_t100_message~t100key = lcx_no_connection.
ELSE.
if_t100_message~t100key = textid.
ENDIF.
ENDMETHOD.
ENDCLASS.
2、调用
在lcx_no_connection
之后,继续添加以下代码。查询/dmo/connection
,在记录不存在的情况下,抛出自定义异常。
CLASS lcl_connection DEFINITION.
PUBLIC SECTION.
METHODS constructor
IMPORTING
i_airlineid TYPE /dmo/carrier_id
i_connectionnumber TYPE /dmo/connection_id
RAISING lcx_no_connection.
PROTECTED SECTION.
PRIVATE SECTION.
DATA airlineid TYPE /dmo/carrier_id.
DATA connectionnumber TYPE /dmo/connection_id.
DATA fromairport TYPE /dmo/airport_from_id.
DATA toairport TYPE /dmo/airport_to_id.
ENDCLASS.
CLASS lcl_connection IMPLEMENTATION.
METHOD constructor.
DATA fromairport TYPE /dmo/airport_from_id.
DATA toairport TYPE /dmo/airport_to_id.
SELECT SINGLE FROM /dmo/connection
FIELDS airport_from_id, airport_to_id
WHERE carrier_id = @i_airlineid
AND connection_id = @i_connectionnumber
INTO ( @fromairport, @toairport ).
IF sy-subrc <> 0.
RAISE EXCEPTION TYPE lcx_no_connection
EXPORTING
airlineid = i_airlineid
connectionnumber = i_connectionnumber.
ELSE.
me->airlineid = i_airlineid.
me->connectionnumber = i_connectionnumber.
me->fromairport = fromairport.
me->toairport = toairport.
ENDIF.
ENDMETHOD.
ENDCLASS.
3、测试
在main
方法中添加以下代码,执行。
DATA connection TYPE REF TO lcl_connection.
DATA exception TYPE REF TO lcx_no_connection.
TRY.
connection = NEW #( i_airlineid = 'XX' i_connectionnumber = '0000' ).
CATCH lcx_no_connection INTO exception.
out->write( exception->get_text( ) ).
ENDTRY.
总结
打完收工。