Home

EXIT WHEN should be used rather than IF ... THEN EXIT; END IF

Description

    The EXIT WHEN code rule states that the EXIT statement should be used instead of IF ... THEN EXIT; END IF when exiting a loop. This is because the EXIT WHEN statement is more concise and easier to read than the IF ... THEN EXIT; END IF syntax. Additionally, the EXIT WHEN statement is more efficient as it does not require the PL/SQL engine to evaluate the condition before exiting the loop.

Key Benefits

  • Simplicity: EXIT WHEN provides a simpler and more concise way of exiting a loop than IF ... THEN EXIT; END IF.
  • Readability: EXIT WHEN is much easier to read and understand than IF ... THEN EXIT; END IF.
  • Performance: EXIT WHEN is more efficient than IF ... THEN EXIT; END IF, since it does not need to evaluate the condition each time it is encountered.

 

Non-compliant Code Example

DECLARE errorLog_ EXCEPTION; 
BEGIN
	FOR i IN 1 .. CUSTOMER_TABLE.COUNT  --Non compliant code (EXIT is used within loop)
		LOOP
            IF CUSTOMER_TABLE(i).Id > 25 THEN 
				EXIT;
			ELSIF CUSTOMER_TABLE(i) IS NOT NULL THEN
				DBMS_OUTPUT.PUT( i || ' = (' || CUSTOMER_TABLE(i).Name || ', ' || CUSTOMER_TABLE(i).PhoneNumber || ')' );
			END IF;
		END LOOP;
EXCEPTION
  WHEN ERRORS THEN
	RETURN;
END CUSTOMER_TABLE_ITERATION;

Compliant Code Example

DECLARE errorLog_ EXCEPTION; 
BEGIN
	FOR i IN 1 .. CUSTOMER_TABLE.COUNT  --Compliant code (EXIT When is used within loop)
		LOOP
			EXIT WHEN CUSTOMER_TABLE(i).Id > 25; 
				
			IF CUSTOMER_TABLE(i) IS NOT NULL THEN
				DBMS_OUTPUT.PUT( i || ' = (' || CUSTOMER_TABLE(i).Name || ', ' || CUSTOMER_TABLE(i).PhoneNumber || ')' );
			END IF;
		END LOOP;
EXCEPTION
  WHEN ERRORS THEN
	RETURN;
END CUSTOMER_TABLE_ITERATION;
Visual Expert 2024
 VEPLSQLRULE82