Exforsys

Home arrow Technical Training arrow Oracle 11g Tutorial

Oracle 11g Exception Handling

Page 1 of 2
Author:      Published on: 9th Jun 2011

Exception can be defined as the state of an entity, which is different from its conventional and normal behavior. In context to programming language, exception refers to the abnormal situation in the normal flow of the program. Oracle server raises exception whenever it encounters a logical violation of the flow during program execution.

I have listed the common situations which end up raising exceptions and subsequently termination of the program.

  1. Design Faults and illogical flow
  2. Exception propagation from referenced program unit
  3. Coding mistakes
  4. Hardware failures

Exception Propagation in a Program Unit

The figure below shows the program flow, which is followed when an exception situation occurs in the PL/SQL block and the exception has been handled. Once the exception has been raised and trapped, and the control moves to EXCEPTION section, the program propagates in the forward direction.

If the exception has not been handled, the program terminates abruptly or propagates to the calling environment.

Fig 1a: Program flow when the Exception has been trapped and handled

Fig 1b: Program flow when the Exception has not been handled

Exception Handling

Exceptions can be trapped in the EXCEPTION section of a PL/SQL block. Oracle supports two ways to raise exception in a program, implicitly or explicitly.

Exceptions which are automatically raised by the oracle server fall under the category of implicit way raising an exception. PL/SQL runtime engine identifies the abnormal flow and raises the exception. For example, NO_DATA_FOUND or TOO_MANY_ROWS are the system defined exceptions which are raised by the server during program execution.

Exceptions which are trapped in executable section and handled in the EXCEPTION block by the programmer are explicit ways raising exceptions. In this category, a user can either explicitly raise an already existing system defined exception or create a new exception and invoke in the program.

Syntax [1]

Sample Code
  1. EXCEPTION
  2.   WHEN exception1 [OR exception2 . . .] THEN
  3.     statement1;
  4.     statement2;
  5.     . . .
  6.   [WHEN exception3 [OR exception4 . . .] THEN
  7.     statement1;
  8.     statement2;
  9.     . . .]
  10.   [WHEN OTHERS THEN
  11.     statement1;
  12.     statement2;
  13.     . . .]
Copyright exforsys.com


In the syntax, a single WHEN-THEN statement is called as Exception Handler. Likewise, there can be multiple exception handlers in the EXCEPTION section of a PL/SQL block. An exception handler consists of exception name and set of statements, which would be executed once the exception has been raised. An exception handler can have more than one exception aligned using OR operator. So, the same action would be applicable for multiple exceptions.

Out of multiple exception handlers, only one can be executed at a time before the termination of the block.

One exception handler handles a single exception. Repetitive handling of an exception is not allowed in a single block.

Exception Trapping Functions: SQLCODE and SQLERRM

Oracle uses two built in functions for catching exceptions and getting its information, SQLCODE and SQLERRM.

SQLCODE returns the error number for the latest occurred exception in the PL/SQL block, while SQLERRM returns the error message associated with the latter error number.

Code [1]:

The screen dump below shows the usage of SQLCODE and SQLERRM in a program.

Pre Defined Exceptions

Oracle maintains set of defined exceptions, which are implicitly raised by the server, if an abnormal situation occurs in the program. The table below lists some of the commonly occurring exceptions.

Error

Named Exception

ORA-00001

DUP_VAL_ON_INDEX

ORA-01001

INVALID_CURSOR

ORA-01012

NOT_LOGGED_ON

ORA-01017

LOGIN_DENIED

ORA-01403

NO_DATA_FOUND

ORA-01422

TOO_MANY_ROWS

ORA-01476

ZERO_DIVIDE

ORA-01722

INVALID_NUMBER

ORA-06504

ROWTYPE_MISMATCH

ORA-06511

CURSOR_ALREADY_OPEN

ORA-06530

ACCESS_INTO_NULL

ORA-06531

COLLECTION_IS_NULL

ORA-06532

SUBSCRIPT_OUTSIDE_LIMIT

ORA-06533

SUBSCRIPT_BEYOND_COUNT

Raising Exceptions Implicitly

These exceptions are automatically processed and raised by Oracle server.

As soon as Oracle server encounters any illogical flow in the program flow, it stops further execution of program, identifies and throws the appropriate exception; program terminates abruptly.

Refer the example illustration below.

Code [2]:

In the below PL/SQL block, a test message is displayed before and after the SELECT statement. The SELECT statement selects multiple rows through an SQL cursor. Since the query returns multiple rows, it raises an exception. As soon as the exception is raised, control jumps to the EXCEPTION section, skipping the further statements in executable section of the block. The message after the query was not displayed.

Sample Code
  1. DECLARE
  2.    L_DEPTID NUMBER := 10;
  3.    L_ENAME VARCHAR2(100);
  4.    L_SAL NUMBER;
  5. BEGIN
  6.    DBMS_OUTPUT.PUT_LINE('Before SQL query');
  7.    
  8.    SELECT EMPLOYEE_NAME,SALARY
  9.    INTO L_ENAME, L_SAL
  10.    FROM EMPLOYEES
  11.    WHERE DEPARTMENT_ID = L_DEPTID;
  12.    
  13.    DBMS_OUTPUT.PUT_LINE('After SQL query');
  14. END;
  15. /
  16.  
  17. Before SQL query
  18. DECLARE
  19. *
  20. ERROR at line 1:
  21. ORA-01422: exact fetch returns more than requested number of rows
  22. ORA-06512: at line 7
Copyright exforsys.com


The above block also complies with the fact that the once the exception scenario is identified, server skips the execution of the further statements in the block and terminates immediately. For this reason, the second test message doesn’t appear in the output.

Raising Exception Explicitly: System Defined and User Defined Exceptions

A developer can explicitly raise the system defined exceptions. In the Code [], the TOO_MANY_ROWS exception can be captured by defining an exception handler in the EXCEPTION section.

Code [3]

In the below PL/SQL code, TOO_MANY_ROWS exception has been explicitly trapped by the developer bypass the situation (abnormal termination) with an informative message in the application.

Sample Code
  1. DECLARE
  2.    L_DEPTID NUMBER := 10;
  3.    L_ENAME VARCHAR2(100);
  4.    L_SAL NUMBER;
  5. BEGIN
  6.    DBMS_OUTPUT.PUT_LINE('Before SQL query');
  7.    SELECT EMPLOYEE_NAME,SALARY
  8.    INTO L_ENAME, L_SAL
  9.    FROM EMPLOYEES
  10.    WHERE DEPARTMENT_ID = L_DEPTID;
  11.    DBMS_OUTPUT.PUT_LINE('After SQL query');
  12. EXCEPTION
  13.    WHEN TOO_MANY_ROWS THEN
  14.      DBMS_OUTPUT.PUT_LINE ('Use Oracle Bulk Collect feature or Cursor to select multiple rows from a table');
  15. END;
  16. /
  17.  
  18. Before SQL query
  19. USE Oracle Bulk Collect feature OR Cursor TO SELECT multiple rows FROM a TABLE
  20.  
  21. PL/SQL procedure successfully completed.
Copyright exforsys.com


An exception handler may contain alternate operations to be performed at the situations of exception in the program.

System defined exceptions can be the part of business logic too. If a business logic implementation or conditional logic requires a system defined exception to be raised, it can be achieved using RAISE statement. Check the example below.

Code [4]:

Oracle raises NO_DATA_FOUND exception, when the SQL query in the executable section returns no records. To avoid the exception, it can be rewritten using a PL/SQL cursor, without omitting the exception action. System defined exception can be explicitly raised by the programmer like below.

Ads

Sample Code
  1. DECLARE
  2.    L_DEPTID NUMBER := 15;
  3.    L_ENAME VARCHAR2(100);
  4.    L_SAL NUMBER;
  5. CURSOR C IS
  6.    SELECT EMPLOYEE_NAME,SALARY
  7.    FROM EMPLOYEES
  8.    WHERE DEPARTMENT_ID = L_DEPTID;
  9. BEGIN
  10.    DBMS_OUTPUT.PUT_LINE('Before SQL query');
  11.    OPEN C;
  12.    FETCH C INTO L_ENAME, L_SAL;
  13.    IF C%ROWCOUNT = 0 THEN
  14.       RAISE NO_DATA_FOUND;
  15.    END IF;
  16.    CLOSE C;
  17.    DBMS_OUTPUT.PUT_LINE('After SQL query');
  18. EXCEPTION
  19.    WHEN NO_DATA_FOUND THEN
  20.      DBMS_OUTPUT.PUT_LINE ('No Employees in the department');
  21. END;
  22. /
  23.  
  24. Before SQL query
  25. No Employees IN the department
  26.  
  27. PL/SQL procedure successfully completed.
Copyright exforsys.com




 
This tutorial is part of a Oracle 11g Tutorial tutorial series. Read it from the beginning and learn yourself.

Oracle 11g Tutorial

 

Comments