When an exception occur a message which explains its cause is received. PL/SQL Exception message consists of three parts.



Similar documents
Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Handling Exceptions. Schedule: Timing Topic 45 minutes Lecture 20 minutes Practice 65 minutes Total

Handling Exceptions. Schedule: Timing Topic. 45 minutes Lecture 20 minutes Practice 65 minutes Total

Oracle For Beginners Page : 1

STUDY OF PL/SQL BLOCK AIM: To Study about PL/SQL block.

Handling PL/SQL Errors

Handling Exceptions. Copyright 2008, Oracle. All rights reserved.

Handling PL/SQL Errors

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.


Chapter 8: Introduction to PL/SQL 1

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals NEW

Topics Advanced PL/SQL, Integration with PROIV SuperLayer and use within Glovia

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

Database Programming with PL/SQL: Learning Objectives

Oracle Database: SQL and PL/SQL Fundamentals

Oracle 11g PL/SQL training

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

DECLARATION SECTION. BODY STATEMENTS... Required

Creating PL/SQL Blocks. Copyright 2007, Oracle. All rights reserved.

Database programming 20/08/2015. DBprog news. Outline. Motivation for DB programming. Using SQL queries in a program. Using SQL queries in a program

Oracle Database 11g Express Edition PL/SQL and Database Administration Concepts -II

Darshan Institute of Engineering & Technology PL_SQL

PL/SQL (Cont d) Let s start with the mail_order database, shown here:

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

COMS20700 DATABASES 13 PL/SQL. COMS20700 Databases Dr. Essam Ghadafi

Oracle Database: SQL and PL/SQL Fundamentals NEW

CSC 443 Database Management Systems. The SQL Programming Language

Oracle For Beginners Page : 1

Answers to the Try It Yourself Sections

PROCEDURES, FUNCTIONS AND PACKAGES

Oracle PL/SQL Best Practices

Introduction to PL/SQL Programming

A basic create statement for a simple student table would look like the following.

Oracle 10g PL/SQL Training

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Oracle Database 10g: Program with PL/SQL

PL/SQL MOCK TEST PL/SQL MOCK TEST I

Oracle PL/SQL Language. CIS 331: Introduction to Database Systems

Oracle For Beginners Page : 1

Oracle Database: Program with PL/SQL

PL/SQL Programming Concepts: Review. Copyright 2004, Oracle. All rights reserved.

Oracle Database: Program with PL/SQL

Best Practices for Dynamic SQL

OPP ODTUG Kaleidoscope. An ODTUG SP* Oracle PL/SQL Programming Conference. WOW-Wide Open World, Wide Open Web!

Oracle Database: Program with PL/SQL

Making the Most of Oracle PL/SQL Error Management Features

Oracle Database: Program with PL/SQL

Training Guide. PL/SQL for Beginners. Workbook

Oracle Database 11g: Program with PL/SQL

Oracle SQL. Course Summary. Duration. Objectives

Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts

Oracle Database: Develop PL/SQL Program Units

PL/SQL TUTORIAL. Simply Easy Learning by tutorialspoint.com. tutorialspoint.com

Oracle Database 12c: Introduction to SQL Ed 1.1

Writing Control Structures

Oracle PL/SQL Programming

Querying Microsoft SQL Server

PL / SQL Basics. Chapter 3

Oracle Database: Program with PL/SQL

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

Oracle Database 10g: Introduction to SQL

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Database SQL messages and codes

Course ID#: W 35 Hrs. Course Content

Querying Microsoft SQL Server 20461C; 5 days

Oracle Database: Introduction to SQL

Oracle Internal & Oracle Academy

Overview of PL/SQL. About PL/SQL

Oracle Database: Introduction to SQL

Querying Microsoft SQL Server Course M Day(s) 30:00 Hours

Oracle Database 11g SQL

Schema Evolution in SQL-99 and Commercial (Object-)Relational DBMS

Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement

C H A P T E R Condition Handling

1. INTRODUCTION TO RDBMS

MOC QUERYING MICROSOFT SQL SERVER

Error Management in Oracle PL/SQL

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

Oracle Database: Introduction to SQL

How To Name A Program In Apl/Sql

Introducing Microsoft SQL Server 2012 Getting Started with SQL Server Management Studio

Oracle Database Security

2. Which of the following declarations is invalid? Mark for Review (1) Points

MOC 20461C: Querying Microsoft SQL Server. Course Overview

INFORMATION BROCHURE Certificate Course in Web Design Using PHP/MySQL

Micro Focus Database Connectors

Programming with SQL

Instant SQL Programming

Nested Blocks and Variable Scope. Copyright 2007, Oracle. All rights reserved.

The first time through running an Ad Hoc query or Stored Procedure, SQL Server will go through each of the following steps.

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

14 Triggers / Embedded SQL

Data Masking. Procedure

Transcription:

ERROR HANDLING IN PLSQL When an SQL statement fails, the Oracle engine recognizes this as an Exception Condition. What is Exception Handling? PLSQL provides a feature to handle the Exceptions which occur in a PLSQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting immediately. When an exception occur a message which explains its cause is received. PLSQL Exception message consists of three parts. 1) Type of Exception 2) An Error Code 3) A message By handling the exceptions we can ensure a PLSQL block does not exit immediately. Structure of Exception Handling. General Syntax for coding the exception section Declaration section Exception section WHEN ex_name1 THEN -Error handling statements WHEN ex_name2 THEN -Error handling statements WHEN Others THEN -Error handling statements Types of Exception. There are 3 types of Exceptions. a) Named System Exceptions b) Unnamed System Exceptions c) User-defined Exceptions

ORACLE S NAMED HANDLERS System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule. There are some system exceptions which are raised frequently, so they are pre-defined and given a name in Oracle which is known as Named System Exceptions. The Oracle engine has around fifteen to twenty named exception handlers. These are not identified by names but by four integers preceded by a hyphen (-). E.g. -1489. The exception handler names are actually the set of negative signed integers. Each exception handler has a code attached that will resolve an exception condition. This is how Oracle s Default Exception-Handling works. Named system exceptions are: Not Declared explicitly, Raised implicitly when a predefined Oracle error occurs, Caught by referencing the standard name within an exception-handling routine. Following are some of the predefined Oracle named exception handlers. Exception ACCESS_INTO_NULL CASE_NOT_FOUND Description It is raised when a null object is automatically assigned a value. It is raised when none of the choices in the WHEN clauses of a CASE statement is selected, and there is no ELSE clause. COLLECTION_IS_NULL It is raised when a program attempts to apply collection methods other than EXISTS to an uninitialized nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray. DUP_VAL_ON_INDEX INVALID_CURSOR INVALID_NUMBER It is raised when duplicate values are attempted to be stored in a column with unique index. It is raised when attempts are made to make a cursor operation that is not allowed, such as closing an unopened cursor. It is raised when the conversion of a character string into a number fails because the string does not represent a valid number. LOGIN_DENIED It is raised when program attempts to log on to the database with an invalid username or password. NO_DATA_FOUND It is raised when a SELECT INTO statement returns no rows. NOT_LOGGED_ON It is raised when a database call is issued without being connected to the database. PROGRAM_ERROR It is raised when PLSQL has an internal problem. ROWTYPE_MISMATCH It is raised when a cursor fetches value in a variable having

SELF_IS_NULL STORAGE_ERROR TOO_MANY_ROWS VALUE_ERROR ZERO_DIVIDE OTHERS incompatible data type. It is raised when a member method is invoked, but the instance of the object type was not initialized. It is raised when PLSQL ran out of memory or memory was corrupted. It is raised when s SELECT INTO statement returns more than one row. It is raised when an arithmetic, conversion, truncation, or sizeconstraint error occurs. It is raised when an attempt is made to divide a Stands for all other exceptions not explicitly named. Example Let us write some simple code to illustrate the concept. We will be using the CUSTOMERS table we had created and used in the previous chapters: c_id customers.id%type: = 8; c_name customers.name%type; c_addr customers.address%type; SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id; DBMS_OUTPUT.PUT_LINE ('Name: ' c_name); DBMS_OUTPUT.PUT_LINE ('Address: ' c_addr); WHEN NO_DATA_FOUND THEN dbms_output.put_line ('No such customer!'); WHEN OTHERS THEN dbms_output.put_line ('Error!'); When the above code is executed at SQL prompt, it produces the following result: No such customer! PLSQL procedure successfully completed. The above program displays the name and address of a customer whose ID is given. Since there is no customer with ID value 8 in our database, the program raises the run-time exception NO_DATA_FOUND, which is captured in block.

Unnamed System Exceptions (USER-Named Exception Handlers) Those system exception for which oracle does not provide a name is known as unnamed system exception. These exceptions do not occur frequently. These exceptions have a code and an associated message. There are two ways to handle unnamed system exceptions: By using the WHEN OTHERS exception handler, or By associating the exception code to a name and using it as a named exception. We can assign a name to unnamed system exceptions using a Pragma called _INIT. _INIT will associate a predefined Oracle error number to a programmer_defined exception name. Steps to be followed to use unnamed system exceptions are They are raised implicitly. If they are not handled in WHEN OTHERS must be handled explicitly. To handle the exception explicitly, they must be declared using Pragma _INIT as given above and handled referencing the user-defined exception name in the exception section. The general syntax to declare unnamed system exception using _INIT is exception_name ; PRAGMA _INIT (Exception_name, Error_code); Execution section WHEN exception_name THEN handle the exception For Example: Lets consider the product table and order_items table from sql joins. Here product_id is a primary key in product table and a foreign key in order_items table. If we try to delete a product_id from the product table when it has child records in order_id table an exception will be thrown with oracle code number -2292.

We can provide a name to this exception and handle it in the exception section as given below. Child_rec_exception ; PRAGMA _INIT (Child_rec_exception, -2292); Delete FROM product where product_id= 104; WHEN Child_rec_exception THEN Dbms_output.put_line('Child records are present for this product_id.'); c) User-defined Exceptions Apart from system exceptions we can explicitly define exceptions based on business rules. These are known as user-defined exceptions. Steps to be followed to use user-defined exceptions: They should be explicitly declared in the declaration section. They should be explicitly raised in the Execution Section. They should be handled by referencing the user-defined exception name in the exception section. EXAMPLE The following example illustrates the concept. This program asks for a customer ID, when the user enters an invalid ID, the exception invalid_id is raised. c_id customers.id%type := &cc_id; c_name customers.name%type; c_addr customers.address%type; -- user defined exception ex_invalid_id ; IF c_id <= 0 THEN RAISE ex_invalid_id; ELSE SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id; DBMS_OUTPUT.PUT_LINE ('Name: ' c_name); DBMS_OUTPUT.PUT_LINE ('Address: ' c_addr); END IF;

WHEN ex_invalid_id THEN dbms_output.put_line('id must be greater than zero!'); WHEN no_data_found THEN dbms_output.put_line('no such customer!'); WHEN others THEN dbms_output.put_line('error!'); When the above code is executed at SQL prompt, it produces the following result: Enter value for cc_id: -6 (let's enter a value -6) old 2: c_id customers.id%type := &cc_id; new 2: c_id customers.id%type := -6; ID must be greater than zero! PLSQL procedure successfully completed. RAISE_APPLICATION_ERROR ( ) RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the user-defined error messages along with the error number whose range isin between -20000 and -20999. Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous transactions, which are not committed within the PLSQL Block, are rolled back automatically (i.e. change due to INSERT, UPDATE, or DELETE statements). RAISE_APPLICATION_ERROR raises an exception but does not handle it. RAISE_APPLICATION_ERROR is used for the following reasons, a) to create a unique id for an user-defined exception. b) to make the user-defined exception look like an Oracle error. The General Syntax to use this procedure is: RAISE_APPLICATION_ERROR (error_number, error_message); The Error number must be between -20000 and -20999 The Error_message is the message you want to display when the error occurs.

Steps to be followed to use RAISE_APPLICATION_ERROR procedure: 1. Declare a user-defined exception in the declaration section. 2. Raise the user-defined exception based on a specific business rule in the execution section. 3. Finally, catch the exception and link the exception to a user-defined error number in RAISE_APPLICATION_ERROR. Example Using the above example we can display a error message using RAISE_APPLICATION_ERROR. c_id customers.id%type := &cc_id; c_name customers.name%type; c_addr customers.address%type; -- user defined exception ex_invalid_id ; IF c_id <= 0 THEN RAISE ex_invalid_id; ELSE SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id; DBMS_OUTPUT.PUT_LINE ('Name: ' c_name); DBMS_OUTPUT.PUT_LINE ('Address: ' c_addr); END IF; WHEN ex_invalid_id THEN raise_application_error(-20101, 'Invalid Customer Id');