Open In App

Exception Handling in PL/SQL

An exception is an error which disrupts the normal flow of program instructions. PL/SQL provides us the exception block which raises the exception thus helping the programmer to find out the fault and resolve it.

There are two types of exceptions defined in PL/SQL



  1. User defined exception.
  2. System defined exceptions.

Syntax to write an exception

WHEN exception THEN 
    statement;

DECLARE
declarations section;



BEGIN
executable command(s);

EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code */

END;

Note:
When other keyword should be used only at the end of the exception handling block as no exception handling part present later will get executed as the control will exit from the block after executing the WHEN OTHERS.

  1. System defined exceptions:

  2. These exceptions are predefined in PL/SQL which get raised WHEN certain database rule is violated.
    System-defined exceptions are further divided into two categories:
    1. Named system exceptions.
    2. Unnamed system exceptions.




  • User defined exceptions:
    This type of users can create their own exceptions according to the need and to raise these exceptions explicitly raise command is used.

    Example:

    • Divide non-negative integer x by y such that the result is greater than or equal to 1.

      From the given question we can conclude that there exist two exceptions

      • Division be zero.
      • If result is greater than or equal to 1 means y is less than or equal to x.




      DECLARE
         x int:=&x; /*taking value at run time*/
         y int:=&y;
         div_r float;
         exp1 EXCEPTION;
         exp2 EXCEPTION;
        
      BEGIN
         IF y=0 then
             raise exp1;
        
         ELSEIF y > x then
            raise exp2;
        
         ELSE
            div_r:= x / y;
            dbms_output.put_line('the result is '||div_r);
        
         END IF;
        
      EXCEPTION
         WHEN exp1 THEN
            dbms_output.put_line('Error');
            dbms_output.put_line('division by zero not allowed');
        
         WHEN exp2 THEN
            dbms_output.put_line('Error');
            dbms_output.put_line('y is greater than x please check the input');
        
      END;
      
      
      Input 1: x = 20
               y = 10
      
      Output: the result is 2
      
      Input 2: x = 20
               y = 0
      
      Output:
      Error
      division by zero not allowed
      
      Input 3: x=20
               y = 30
      
      Output:
      Error
      y is greater than x please check the input
      

    RAISE_APPLICATION_ERROR:
    It is used to display user-defined error messages with error number whose range is in between -20000 and -20999. When RAISE_APPLICATION_ERROR executes it returns error message and error code which looks same as Oracle built-in error.

    Example:




    DECLARE
        myex EXCEPTION;
        n NUMBER :=10;
      
    BEGIN
        FOR i IN 1..n LOOP
        dbms_output.put_line(i*i);
            IF i*i=36 THEN
            RAISE myex;
            END IF;
        END LOOP;
      
    EXCEPTION
        WHEN myex THEN
            RAISE_APPLICATION_ERROR(-20015, 'Welcome to GeeksForGeeks');
      
    END;
    
    

    Output:

    Error report:
    ORA-20015: Welcome to GeeksForGeeks
    ORA-06512: at line 13
    
    1
    4
    9
    16
    25
    36
    
    
    

    Note: The output is based on Oracle Sql developer, the output order might change IF you’re running this code somewhere else.

    Scope rules in exception handling:

    1. We can’t DECLARE an exception twice but we can DECLARE the same exception in two dIFferent blocks.
    2. Exceptions DECLAREd inside a block are local to that block and global to all its sub-blocks.

    As a block can reference only local or global exceptions, enclosing blocks cannot reference exceptions DECLAREd in a sub-block.
    If we reDECLARE a global exception in a sub-block, the local declaration prevails i.e. the scope of local is more.

    Example:




    DECLARE
       GeeksforGeeks EXCEPTION;
       age NUMBER:=16;
    BEGIN
      
       --  sub-block BEGINs 
       DECLARE       
            
          -- this declaration prevails 
          GeeksforGeeks  EXCEPTION;  
          age NUMBER:=22;
        
       BEGIN
          IF age > 16 THEN
             RAISE GeeksforGeeks; /* this is not handled*/
          END IF;
         
       END;          
       -- sub-block ends
      
    EXCEPTION
      -- Does not handle raised exception 
      WHEN GeeksforGeeks THEN
        DBMS_OUTPUT.PUT_LINE
          ('Handling  GeeksforGeeks exception.');
        
      WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE
          ('Could not recognize exception GeeksforGeeks  in this scope.');
    END;
    
    

    Output:

    Could not recognize exception GeeksforGeeks  in this scope.
    
  • Advantages:

    From above code we can conclude that exception handling

    1. Improves readability by letting us isolate error-handling routines and thus providing robustness.
    2. Provides reliability, instead of checking for dIFferent types of errors at every point we can simply write them in exception block and IF error exists exception will be raised thus helping the programmer to find out the type of error and eventually resolve it.

    Uses: One of the real lIFe use of exception can be found in online train reservation system.
    While filling the station code to book the ticket IF we input wrong code it shows us the exception that the code doesn’t exist in database.

    Reference: You can find the list of all pre-defined exception here.
    Total number of pre-defined exceptions


    Article Tags :