ABAP exit

Summary: in this tutorial, you will learn how to terminate a loop immediately using the ABAP exit staement.

Introduction to ABAP exit statement

Sometimes, you may want to terminate a loop prematurely. To do this, you use the exit statement in the code block of the loop:

exit.

Typically, you use the exit statement in conjunction with an if statement inside a loop. For example:

do n times.
   " ...
   " terminate the loop
   if condition.
     exit.
   endif.
enddo.

Or when you use the exit statement in a while loop:

while condition.
   " ...
   if condition.
      exit.
   endif.
endwhile.

If you use the exit statement in a nested loop, it will terminate the innermost loop.

Using exit in a do loop

The following shows how to use the exit statement in a do loop:

do 5 times.
  write / sy-index.
  if sy-index = 2.
    exit.
  endif.
enddo.

Output:

1
2

How it works.

  • First, execute the code block 5 times using the do statement.
  • Second, output the current loop index to the screen. If the current loop index is 2, terminate the entire loop by using the exit statement.

Using exit in a while loop

The following illustrates how to use exit statement to terminate a while loop:

data gv_counter type i value 1.

while gv_counter > 0.
  write /  gv_counter.
  gv_counter = gv_counter + 1.
  if gv_counter = 5.
    exit.
  endif.
endwhile.

Summary

  • Use exit statement to terminate an entire loop prematurely.