Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

Oracle 11g Exception Handling

By Saurabh Gupta | on June 9, 2011 |
Oracle 11g Tutorials

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]
EXCEPTION
  WHEN exception1 [OR exception2 . . .] THEN
    statement1;
    statement2;
    . . .
  [WHEN exception3 [OR exception4 . . .] THEN
    statement1;
    statement2;
    . . .]
  [WHEN OTHERS THEN
    statement1;
    statement2;
    . . .]

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.

DECLARE
   L_DEPTID NUMBER := 10;
   L_ENAME VARCHAR2(100);
   L_SAL NUMBER;
BEGIN
   DBMS_OUTPUT.PUT_LINE('Before SQL query');
 
   SELECT EMPLOYEE_NAME,SALARY
   INTO L_ENAME, L_SAL
   FROM EMPLOYEES
   WHERE DEPARTMENT_ID = L_DEPTID;
 
   DBMS_OUTPUT.PUT_LINE('After SQL query');
END;
/
 
BEFORE SQL query
DECLARE
*
ERROR at line 1:
ORA-01422: exact fetch RETURNS more than requested NUMBER OF ROWS
ORA-06512: at line 7

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.

DECLARE
   L_DEPTID NUMBER := 10;
   L_ENAME VARCHAR2(100);
   L_SAL NUMBER;
BEGIN
   DBMS_OUTPUT.PUT_LINE('Before SQL query');
   SELECT EMPLOYEE_NAME,SALARY
   INTO L_ENAME, L_SAL
   FROM EMPLOYEES
   WHERE DEPARTMENT_ID = L_DEPTID;
   DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
   WHEN TOO_MANY_ROWS THEN
     DBMS_OUTPUT.PUT_LINE ('Use Oracle Bulk Collect feature or Cursor to select multiple rows from a table');
END;
/
 
BEFORE SQL query
USE Oracle Bulk Collect feature OR Cursor TO SELECT multiple ROWS FROM a TABLE
 
PL/SQL PROCEDURE successfully completed.

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.

DECLARE
   L_DEPTID NUMBER := 15;
   L_ENAME VARCHAR2(100);
   L_SAL NUMBER;
CURSOR C IS
   SELECT EMPLOYEE_NAME,SALARY
   FROM EMPLOYEES
   WHERE DEPARTMENT_ID = L_DEPTID;
BEGIN
   DBMS_OUTPUT.PUT_LINE('Before SQL query');
   OPEN C;
   FETCH C INTO L_ENAME, L_SAL;
   IF C%ROWCOUNT = 0 THEN
      RAISE NO_DATA_FOUND;
   END IF;
   CLOSE C;
   DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
   WHEN NO_DATA_FOUND THEN
     DBMS_OUTPUT.PUT_LINE ('No Employees in the department');
END;
/
 
BEFORE SQL query
No Employees IN the department
 
PL/SQL PROCEDURE successfully completed.

User Defined Exceptions

User defined exceptions allow the developers to create their own customized exceptions and raise them within the program wherever required. They are declared in the DECLARE section of the block with type as EXCEPTION and raised using RAISE statement.

This feature gives them flexibility to create exception with their convenient name, which can be more handful for use and easy to remember in large formulated applications.

Code [5]:

The PL/SQL block used in the earlier examples has been reused to declare a user defined exception LOCAL_EXCEPTION. It is raised at the same logic (when no employees exist in a department) using RAISE statement.

DECLARE
   L_DEPTID NUMBER := 15;
   L_ENAME VARCHAR2(100);
   L_SAL NUMBER;
   LOCAL_EXCEPTION EXCEPTION;
CURSOR C IS
   SELECT EMPLOYEE_NAME,SALARY
   FROM EMPLOYEES
   WHERE DEPARTMENT_ID = L_DEPTID;
BEGIN
   DBMS_OUTPUT.PUT_LINE('Before SQL query');
   OPEN C;
   FETCH C INTO L_ENAME, L_SAL;
   IF C%ROWCOUNT =0 THEN
      RAISE LOCAL_EXCEPTION;
   END IF;
   CLOSE C;
   DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
   WHEN LOCAL_EXCEPTION THEN
     DBMS_OUTPUT.PUT_LINE ('No Employees in the department');
END;
/
 
BEFORE SQL query
No Employees IN the department
 
PL/SQL PROCEDURE successfully completed.

Associating a User Defined Exception with an Error Number (or Exception Code)

A user defined exception can be associated with an error number using PRAGMA EXCEPTION_INIT. The pragma is a compiler directive which hints the compiler to accept the directions provided in the program. The PRAGMA EXCEPTION_INIT directs the compiler to align the user defined exception with a self assigned error number. The error number must be one of the valid ORA error codes, which are defined by the server.

Syntax [2]
PRAGMA EXCEPTION_INIT([EX NAME],[ERROR NUMBER], [TRUE | FALSE])
Code [6]

In the PL/SQL block below, the LOCAL_EXCEPTION exception is linked with the error number -100 through the PRAGMA EXCEPTION_INIT. Note the usage of SQLCODE, which returns the same associated error number.

DECLARE
   L_DEPTID NUMBER := 15;
   L_ENAME VARCHAR2(100);
   L_SAL NUMBER;
   LOCAL_EXCEPTION EXCEPTION;
   PRAGMA EXCEPTION_INIT(LOCAL_EXCEPTION, -100);
CURSOR C IS
   SELECT EMPLOYEE_NAME,SALARY
   FROM EMPLOYEES
   WHERE DEPARTMENT_ID = L_DEPTID;
BEGIN
   DBMS_OUTPUT.PUT_LINE('Before SQL query');
   OPEN C;
   FETCH C INTO L_ENAME, L_SAL;
   IF C%ROWCOUNT =0 THEN
      RAISE LOCAL_EXCEPTION;
   END IF;
   CLOSE C;
   DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
   WHEN LOCAL_EXCEPTION THEN
     DBMS_OUTPUT.PUT_LINE (‘Exception Error NUMBER:’||SQLCODE);
     DBMS_OUTPUT.PUT_LINE ('No Employees in the department');
END;
/
 
BEFORE SQL query
Exception Error NUMBER:-100
No Employees IN the department
 
PL/SQL PROCEDURE successfully completed.

Customizing the Error Numbers: RAISE_APPLICATION_ERROR

Oracle facilitates the developer by privileging them to create an error number of their own choice and associating them with a customized message. RAISE_APPLICATION_ERROR is an Oracle API, which allows choosing the error numbers in range of -20000 to -20999 and fix them with an error message

It can be used in executable section or exception section in a PL/SQL block.

Syntax [3]
RAISE_APPLICATION_ERROR (error_number, error_message[, {TRUE | FALSE}])
Code [7]
DECLARE
   L_DEPTID NUMBER := 15;
   L_ENAME VARCHAR2(100);
   L_SAL NUMBER;
CURSOR C IS
   SELECT EMPLOYEE_NAME,SALARY
   FROM EMPLOYEES
   WHERE DEPARTMENT_ID = L_DEPTID;
BEGIN
   DBMS_OUTPUT.PUT_LINE('Before SQL query');
   OPEN C;
   FETCH C INTO L_ENAME, L_SAL;
   IF C%ROWCOUNT =0 THEN
      RAISE_APPLICATION_ERROR(-20001,' No Employees in the department');
   END IF;
   CLOSE C;
   DBMS_OUTPUT.PUT_LINE('After SQL query');
END;
/
 
BEFORE SQL query
DECLARE
*
ERROR at line 1:
ORA-20001:  No Employees IN the department
ORA-06512: at line 14
« « Oracle Functions and Procedures
What is Empathy? » »

Author Description

Avatar

Free Training

RSSSubscribe 394 Followers
  • Popular
  • Recent
  • Oracle 11g Collections

    June 2, 2011 - 0 Comment
  • Oracle VPD implementation

    October 24, 2011 - 0 Comment
  • Oracle 11g Result Cache

    April 28, 2011 - 0 Comment
  • PL/Scope and PL/SQL Hierarchical Profiler

    November 6, 2011 - 0 Comment
  • Oracle 11g Read Only Tables

    June 16, 2011 - 0 Comment
  • Oracle Partitioning Overview

    January 17, 2012 - 0 Comment
  • Oracle 11g Subprogram Overloading

    June 17, 2011 - 0 Comment
  • Oracle Analytic Enhancements

    June 19, 2012 - 0 Comment
  • Oracle Functions and Procedures

    June 7, 2011 - 0 Comment
  • Oracle XML Storage

    June 19, 2012 - 0 Comment
  • Oracle XML Storage

    June 19, 2012 - 0 Comment
  • Oracle Analytic Enhancements

    June 19, 2012 - 0 Comment
  • Oracle Partitioning Overview

    January 17, 2012 - 0 Comment
  • PL/Scope and PL/SQL Hierarchical Profiler

    November 6, 2011 - 0 Comment
  • Oracle VPD implementation

    October 24, 2011 - 0 Comment
  • Oracle 11g SecureFiles

    September 4, 2011 - 0 Comment
  • Manage Oracle dependencies

    August 16, 2011 - 0 Comment
  • UTL_FILE

    August 10, 2011 - 0 Comment
  • Oracle Pragma

    July 6, 2011 - 0 Comment
  • Conditional compilation in Oracle PL/SQL

    June 28, 2011 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • Oracle XML Storage
  • Oracle Analytic Enhancements
  • Oracle Partitioning Overview
  • PL/Scope and PL/SQL Hierarchical Profiler
  • Oracle VPD implementation

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT