Exceptions in PL/SQL
In PL/SQL, exceptions are used to handle errors and other exceptional events that occur during the execution of a program. PL/SQL provides predefined exceptions and allows the creation of user-defined exceptions.
Predefined Exceptions
Some common predefined exceptions include:
- NO_DATA_FOUND: Raised when a SELECT INTO statement returns no rows.
- TOO_MANY_ROWS: Raised when a SELECT INTO statement returns more than one row.
- ZERO_DIVIDE: Raised when an attempt is made to divide a number by zero.
- DUP_VAL_ON_INDEX: Raised when a duplicate value is tried to be inserted into a unique column.
User-Defined Exceptions
You can define your own exceptions using the EXCEPTION keyword and handle them using RAISE.
SyntaxHere's the basic syntax for exception handling in PL/SQL:
BEGIN
-- Executable statements
EXCEPTION
WHEN exception1 THEN
-- Exception handling statements for exception1
WHEN exception2 THEN
-- Exception handling statements for exception2
WHEN OTHERS THEN
-- Statements for handling all other exceptions
END;
Example
Below is an example demonstrating the use of predefined and user-defined exceptions:
DECLARE
v_num1 NUMBER := 10;
v_num2 NUMBER := 0;
v_result NUMBER;
e_divide_by_zero EXCEPTION; -- User-defined exception
BEGIN
BEGIN
v_result := v_num1 / v_num2;
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Cannot divide by zero');
RAISE e_divide_by_zero; -- Raise the user-defined exception
END;
EXCEPTION
WHEN e_divide_by_zero THEN
DBMS_OUTPUT.PUT_LINE('User-defined exception: Division by zero');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred');
END;
Tips for Handling Exceptions
- Order of Handling: Specific exceptions should be handled before the OTHERS exception to ensure specific errors are caught first.
- Logging: Use logging mechanisms (such as DBMS_OUTPUT.PUT_LINE or writing to a log table) to record information about exceptions for debugging purposes.
- Rethrowing Exceptions: Sometimes, after handling an exception, you might want to rethrow it to the calling program. You can do this using the RAISE statement.
Exception handling in PL/SQL is a powerful feature that allows developers to handle errors gracefully, ensuring robust and reliable applications. By understanding and properly implementing exception handling, you can create PL/SQL programs that are easier to debug and maintain
Example 1: Handling NO_DATA_FOUND
DECLARE
v_name VARCHAR2(50);
BEGIN
SELECT name INTO v_name FROM employees WHERE employee_id = 999;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee found with ID 999');
END;
Example 2: Handling TOO_MANY_ROWS
DECLAREv_name VARCHAR2(50);
BEGIN
SELECT name INTO v_name FROM employees WHERE department_id = 10;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('More than one employee found in department 10');
END;
Comments
Post a Comment