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');