Search code examples
oracle-databaseplsqlexceptionoracle12c

Stop PL/SQL code after exception (PL/SQL, ORACLE)


I have check procedure:

PROCEDURE checkVariables                               
IS
   r_Var1    exception;
   r_Var2    exception;
BEGIN

 If g_Name is null then     
        RAISE r_Var1;
 End if;
 If g_Prefix is null then     
        RAISE r_Var2;
 End if;

 DBMS_OUTPUT.PUT_LINE('Variables Set Up');

 EXCEPTION
        When r_Var1 then
           DBMS_OUTPUT.PUT_LINE('Missing g_Name');               
        When r_Var2 then
           DBMS_OUTPUT.PUT_LINE('Missing g_Prefix');            
END;

If the exception is raised I want beside message also STOP/BREAK all other PL/SQL code (procedure procedure 3 and 4 will be not executed).

like:

execute procedure1
execute procedure2
execute checkVariables --raised exception, STOP/BREAK next code                               
execute procedure3
execute procedure4

How can I do that?


Solution

  • You could re-raise the exception from your checkVariables procedure. Run all your procedures inside a BEGIN..END with an EXCEPTION block

    ...
    EXCEPTION
      WHEN r_var1 THEN
                 DBMS_OUTPUT.PUT_LINE('Missing g_Name');
                 RAISE; 
    
      WHEN r_var2 THEN
                 DBMS_OUTPUT.PUT_LINE('Missing g_Prefix');
                 RAISE;
    END;
    ... 
    

    BEGIN
    
      procedure1;
      procedure2;
      checkVariables; --raised exception, STOP/BREAK next code                               
      procedure3;
      procedure4; 
    
    EXCEPTION
    
    WHEN  OTHERS THEN 
    
      DBMS_OUTPUT.PUT_LINE('EXCEPTION  OCCURED');
      DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE()); --Gives additional information
    
    END;
    /
    

    Output would be something like this.

    PROC1
    PROC2
    Missing g_Name
    EXCEPTION  OCCURED
    ORA-06512: at "HR.CHECKVARIABLES", line 21
    ORA-06512: at "HR.CHECKVARIABLES", line 10
    ORA-06512: at line 5