Fix CX_SY_ITAB_LINE_NOT_FOUND in ABAP

CX_SY_ITAB_LINE_NOT_FOUND is raised when a table expression such as itab[ id = 5 ] finds no matching row. If nobody catches it, the program ends with the runtime error ITAB_LINE_NOT_FOUND. The quickest fix is VALUE #( itab[ id = 5 ] OPTIONAL ), which returns an initial row instead.
Code that fails
TYPES: BEGIN OF ts_user,
id TYPE i,
name TYPE string,
END OF ts_user.
DATA lt_users TYPE STANDARD TABLE OF ts_user WITH EMPTY KEY.
lt_users = VALUE #( ( id = 1 name = `Emma` ) ( id = 2 name = `John` ) ).
DATA(ls_user) = lt_users[ id = 5 ]. " no row with id 5
Unlike READ TABLE, a table expression that reads a value does not report a missing row through sy-subrc.
Fix 1: OPTIONAL
DATA(ls_user1) = VALUE #( lt_users[ id = 5 ] OPTIONAL ).
IF ls_user1 IS INITIAL.
WRITE / 'No user found'.
ENDIF.
Fix 2: DEFAULT
DATA(ls_user2) = VALUE #( lt_users[ id = 5 ]
DEFAULT VALUE #( id = 0 name = `Guest` ) ).
Fix 3: TRY and CATCH
TRY.
DATA(lv_name) = lt_users[ id = 5 ]-name.
CATCH cx_sy_itab_line_not_found.
lv_name = `Guest`.
ENDTRY.
Use this when a missing row is a real error, or when one block contains several reads.
Fix 4: ASSIGN and sy-subrc
ASSIGN lt_users[ id = 5 ] TO FIELD-SYMBOL(<ls_user>).
IF sy-subrc = 0.
<ls_user>-name = `Changed`.
ENDIF.
In ASSIGN, a missing row sets sy-subrc to 4 and raises no exception. Check it right away. This is the best choice when you want to change the row.
Fix 5: READ TABLE
READ TABLE lt_users INTO DATA(ls_user5) WITH KEY id = 5.
IF sy-subrc <> 0.
WRITE / 'No user found'.
ENDIF.
READ TABLE also works on older releases. Before 7.40, declare ls_user5 with DATA first.
Which fix should you use?
| Situation | Use |
|---|---|
| Missing row is normal, initial value is fine | OPTIONAL |
| A specific fallback is needed | DEFAULT |
| Missing row is an error | TRY ... CATCH |
| You want to change the row | ASSIGN |
| An initial row would also be a valid row | READ TABLE or ASSIGN with sy-subrc |
The last line matters: after OPTIONAL you cannot distinguish “not found” from “found, but empty”.
Avoid this pattern
IF line_exists( lt_users[ id = 1 ] ).
DATA(ls_found) = lt_users[ id = 1 ].
ENDIF.
It is correct, but it searches the table twice. line_exists is meant for the case where you only need the answer yes or no.
Chained expressions
In lt_orders[ id = 1 ]-items[ pos = 10 ] either level can fail. OPTIONAL around the complete chain covers both.
OPTIONAL and DEFAULT require ABAP 7.40 SP08. Table expressions exist since 7.40 SP02.
Sources: Table expressions · Result of a table expression · News for 7.40 SP08