Press "Enter" to skip to content

How To Continue Cursor Loop Processing After Exception In Oracle

You are creating a PL/SQL Procedure in Oracle in which you are doing processing while looping through the cursor and if any error (exception) raises then you don’t want to abort the processing but you want to log the error and to continue the processing.

Below is the example is given to handle such condition, in which I have created two exception sections, first one is to handle the error while cursor loop and the other one is to handle exception outside the cursor loop.

SET SERVEROUTPUT ON;
DECLARE
   CURSOR c_emp
   IS
      SELECT ROWNUM, empno, ename FROM emp;

   vn        NUMBER;
   vsqlcode   VARCHAR2 (20);
   vsqlerrm   VARCHAR2 (4000);
BEGIN
   FOR c IN c_emp
   LOOP
      BEGIN
         IF c.ROWNUM = 3
         THEN
            -- Generate an error at line 3
            vn := 'x';
         END IF;

      EXCEPTION
         WHEN OTHERS
         THEN

            vsqlcode := SQLCODE;
            vsqlerrm := SQLERRM;

            INSERT INTO error_log (error_no, ERROR_TEXT)
                VALUES (vsqlcode, vsqlerrm);
      END;
   END LOOP;

   COMMIT;
EXCEPTION
   WHEN OTHERS
   THEN 
            vsqlcode := SQLCODE;
            vsqlerrm := SQLERRM;

      ROLLBACK;
            INSERT INTO error_log (error_no, ERROR_TEXT)
                VALUES (vsqlcode, vsqlerrm);
      Commit;
END;
Continue Cursor loop processing after an error in Oracle