Home
WHEN OTHERS should not be the only exception handler
Rule description
- WHEN OTHERS should not be the only exception handler
Non-compliant Code Example
BEGIN
FOR i IN 1 .. CUSTOMER_TABLE.COUNT
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 OTHERS THEN --Non compliant code (WHEN OTHERS clause only used for exception handling)
error_message := SQLERRORMSG;
DBMS_OUTPUT.PUT_LINE (error_message);
RETURN;
END CUSTOMER_TABLE_ITERATION;
Compliant Code Example
BEGIN
FOR i IN 1 .. CUSTOMER_TABLE.COUNT
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
error_message := SQLERRORMSG;
DBMS_OUTPUT.PUT_LINE (error_message);
RETURN;
WHEN OTHERS THEN --Compliant code (WHEN OTHERS clause is used along with WHEN ERRORS clause for exception handling)
error_message := SQLERRORMSG;
DBMS_OUTPUT.PUT_LINE (error_message);
RETURN;
END CUSTOMER_TABLE_ITERATION;