HOW TO: Use LINE_EXISTS instead of READ TABLE

This article covers the practical usage of LINE_EXISTS in new ABAP syntax. 

  1. Record Existence Check: LINE_EXISTS in ABAP new syntax is used to check the existence of a record. It is similar to READ TABLE using TRANSPORTING NO FIELDS.

  2. Avoid Runtime Exception: For instance if you try to access a record at index 10  from a table which has only five entries using table expressions, the system will throw a runtime error. LINE_EXISTS is also used to avoid the runtime exception 'CX_SY_ITAB_LINE_NOT_FOUND'.

  3. Readability: replaces the old style of coding with READ TABLE statement.  LINE_EXISTS will make the code look readable and shorter.

Example 1: Use LINE_EXISTS instead of READ TABLE TRANSPORTING NO FIELDS

Old Syntax:

READ TABLE lt_table TRANSPORTING NO FIELDS WITH KEY field1 = 'A'. 

IF sy-subrc = 0.

  DATA(lv_line_index) = sy-tabix.
  DATA(lv_line_exists) = abap_true.
ENDIF.

New Syntax:

 DATA(lv_index) = line_index( lt_table[ key = 'A' ] ).
 DATA(lv_exists) = xsdbool( line_exists( lt_table[ field1 = 'A' ] ) ).

LINE_INDEX is used to get the sy-tabix value.
 
Example 2: Avoiding Runtime Errors When Reading records

Consider the internal table has only 5 entries. Suppose you want to fetch 10th record from internal table

DATA(ls_record) = lt_table[10].

If record doesn't exist it will throw runtime error. To avoid runtime error use below check

IF line_exists( lt_table[10] ).

    DATA(ls_record) = lt_table[10].
    " Process the record
ELSE.

    " Handle the case where the record does not exist
ENDIF.


Important note :

Interviewers might ask you about this point. 

How to avoid runtime error when you read internal table using new syntax ?

As per my knowledge I have 3 options to consider to avoid runtime error
  1. Using LINE_EXISTS( ) before accessing the record.
  2. Using VALUE #( lt_table[ ... ] OPTIONAL ) 
  3. Using TRY CATCH cx_sy_itab_line_not_found exception block
Please add more in comments if there are any other options.

So, based on your requirement whichever suits well go with that based on performance.

Post a Comment

Previous Post Next Post