0% found this document useful (0 votes)
4 views9 pages

309142Lecture Notes 3 -Understanding Exception Handling-1737696975929

This document provides an overview of exception handling in PL/SQL, detailing the types of exceptions, including predefined, non-predefined, and user-defined exceptions. It explains how to handle these exceptions using examples and highlights the differences between system-defined and user-defined exceptions. Additionally, it covers the use of SQLCODE and SQLERRM for error handling, as well as the PRAGMA EXCEPTION_INIT for associating user-defined exceptions with specific Oracle error codes.

Uploaded by

vanshikabhadani7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

309142Lecture Notes 3 -Understanding Exception Handling-1737696975929

This document provides an overview of exception handling in PL/SQL, detailing the types of exceptions, including predefined, non-predefined, and user-defined exceptions. It explains how to handle these exceptions using examples and highlights the differences between system-defined and user-defined exceptions. Additionally, it covers the use of SQLCODE and SQLERRM for error handling, as well as the PRAGMA EXCEPTION_INIT for associating user-defined exceptions with specific Oracle error codes.

Uploaded by

vanshikabhadani7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Fundamentals of SQL and Data Modeling for Web-II

UNIT 3 LECTURE NOTES

Understanding Exception Handling


1. What is an Exception?
An Exception in PL/SQL is a runtime error or warning condition that disrupts the normal flow of
program execution. When such conditions occur, they are raised as exceptions, which can be handled
gracefully using appropriate exception-handling techniques.

Common Causes of Exceptions


●​ Division by zero
●​ Data type mismatches
●​ Attempting to insert duplicate values into a unique column
●​ Accessing non-existent rows in a query
●​ Violating integrity constraints

Types of Exceptions in PL/SQL


1.​ Predefined Exceptions: Built-in exceptions automatically raised by the system for common
errors.

Exception Name Error Code Description

NO_DATA_FOUND ORA-01403 No rows returned by a query.

Query returns more than one row in a


TOO_MANY_ROWS ORA-01422
SELECT INTO statement.

ZERO_DIVIDE ORA-01476 Division by zero attempted.

Attempt to use an unopened or closed


INVALID_CURSOR ORA-01001
cursor.

VALUE_ERROR ORA-06502 Data type or conversion error.

2.​ Non-predefined Exceptions: Errors that do not have predefined names but can be declared
by the programmer using error codes.
DECLARE
my_custom_exception EXCEPTION;
PRAGMA EXCEPTION_INIT(my_custom_exception, -20001);

3.​ User-defined Exceptions: Custom exceptions created by the programmer to handle specific
conditions in the application logic.
Example: Predefined Exception Handling
DECLARE

v_dividend NUMBER := 10;


v_divisor NUMBER := 0;
v_result NUMBER;
BEGIN
v_result := v_dividend / v_divisor; -- Division by zero raises an
exception
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Division by zero is not allowed.');
END;

Handling User-Defined Exceptions


1.​ Declare the exception in the DECLARE section.
2.​ Raise the exception using the RAISE statement.
3.​ Handle the exception in the EXCEPTION block.
Example of User-Defined Exception
DECLARE
insufficient_balance EXCEPTION;
v_balance NUMBER := 500;
v_withdrawal NUMBER := 600;
BEGIN
IF v_withdrawal > v_balance THEN
RAISE insufficient_balance;
END IF;
EXCEPTION
WHEN insufficient_balance THEN
DBMS_OUTPUT.PUT_LINE('Error: Insufficient balance for the
withdrawal.');
END;

1. Handling System-Defined Exceptions in PL/SQL:


System-defined exceptions are built-in exceptions that are automatically raised by Oracle when
certain predefined error conditions occur. These include errors such as division by zero, value too
large for a column, or attempting to select from an empty table.
Common System-Defined Exceptions:
●​ 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 a division by zero occurs.
●​ DUP_VAL_ON_INDEX: Raised when attempting to insert a duplicate value in a column with a
unique constraint.
Example: Handling System-Defined Exceptions:
BEGIN
-- Code that might cause an error
SELECT salary INTO v_salary
FROM employees
WHERE employee_id = 999; -- Assume employee_id 999 doesn't exist

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No data found for this employee ID.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Query returned more than one row.');
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Division by zero error occurred.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred: ' ||
SQLERRM);
END;
Explanation:
●​ In this example, system-defined exceptions like NO_DATA_FOUND, TOO_MANY_ROWS, and
ZERO_DIVIDE are handled in the EXCEPTION section.
●​ The OTHERS handler catches any other exceptions that are not explicitly listed.

2. Handling User-Defined Exceptions in PL/SQL:


User-defined exceptions are those that you define in your PL/SQL block to represent specific error
conditions in your application. These exceptions are raised when a specific error or condition occurs
that is not covered by the system-defined exceptions.
Steps to Handle User-Defined Exceptions:
1.​ Declare the exception: Declare the exception in the declaration section of the PL/SQL block.
2.​ Raise the exception: Use the RAISE statement to trigger the exception when a certain
condition is met.
3.​ Handle the exception: Catch the exception in the EXCEPTION section and respond
accordingly.
Example: Handling User-Defined Exceptions:
DECLARE
-- Declare the user-defined exception
invalid_salary EXCEPTION;
v_salary NUMBER;
BEGIN
-- Code that might raise an exception
v_salary := 5000;
-- Check a condition and raise the exception
IF v_salary < 10000 THEN
RAISE invalid_salary; -- Raising the user-defined exception
END IF;
EXCEPTION
WHEN invalid_salary THEN
DBMS_OUTPUT.PUT_LINE('Salary is below the required amount.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred: ' || SQLERRM);
END;
Explanation:
●​ The exception invalid_salary is defined in the DECLARE section.
●​ In the BEGIN section, a check is performed to see if the salary is below the threshold, and if
so, the exception is raised.
●​ The exception is then handled in the EXCEPTION section where it is caught, and a message is
displayed.

Key Differences Between System-Defined and User-Defined Exceptions:

Feature System-Defined Exceptions User-Defined Exceptions

Predefined by Oracle, such as Defined by the programmer for


Definition
NO_DATA_FOUND or ZERO_DIVIDE. specific error conditions.

Raised explicitly by the


Automatically raised by Oracle during
Usage programmer using the RAISE
runtime.
statement.

TOO_MANY_ROWS, NO_DATA_FOUND,
Example invalid_salary, under_age.
DUP_VAL_ON_INDEX.

Handled in the EXCEPTION section with Handled similarly, but you must
Handling
specific exceptions. declare the exception first.

1. SQLCODE vs SQLERRM in PL/SQL:


Both SQLCODE and SQLERRM are used to retrieve information about errors in PL/SQL, but they
provide different kinds of details.
SQLCODE:
●​ SQLCODE is a built-in function in PL/SQL that returns the error number associated with the
last exception raised during the execution of a PL/SQL block.
●​ It returns a negative value for error codes (e.g., -20001 for a user-defined error) and 0 when
no error occurs.
SQLERRM:
●​ SQLERRM is a built-in function in PL/SQL that returns the error message associated with the
last exception raised.
●​ It provides a descriptive error message that corresponds to the error number (e.g.,
"ORA-01400: cannot insert NULL into ('EMPLOYEES', 'SALARY')").
Example of Using SQLCODE and SQLERRM:
BEGIN
-- Code that causes an error
INSERT INTO employees (employee_id, salary)
VALUES (1, NULL); -- Assuming salary cannot be NULL

EXCEPTION
WHEN OTHERS THEN
-- Use SQLCODE to get the error number
DBMS_OUTPUT.PUT_LINE('Error code: ' || SQLCODE);

-- Use SQLERRM to get the error message


DBMS_OUTPUT.PUT_LINE('Error message: ' || SQLERRM);
END;

Explanation:
●​ When an error occurs in the INSERT statement (because salary cannot be NULL), the
exception is caught by the WHEN OTHERS handler.
●​ SQLCODE returns the error number associated with the INSERT failure, and SQLERRM
provides the corresponding error message.
Key Differences:

Feature SQLCODE SQLERRM

Returns Error number (integer) Error message (string)

SQLCODE = -1400 (for NULL SQLERRM = 'ORA-01400: cannot insert NULL into
Example
insertion error) ("EMPLOYEES", "SALARY")'

Used to get the error


Use Used to get the detailed error message
number

2. PRAGMA EXCEPTION_INIT in PL/SQL:


PRAGMA EXCEPTION_INIT is used in PL/SQL to associate a user-defined exception with a specific
Oracle error code. This allows you to handle specific Oracle errors by raising custom exceptions.
Syntax:
PRAGMA EXCEPTION_INIT(exception_name, error_code);
●​ exception_name: The name of the user-defined exception that will be raised.
●​ error_code: The Oracle error number (e.g., -1, -20001).
Example of Using PRAGMA EXCEPTION_INIT:
DECLARE
-- Declare a user-defined exception
salary_too_low EXCEPTION;

-- Use PRAGMA EXCEPTION_INIT to associate the exception with


Oracle error
PRAGMA EXCEPTION_INIT(salary_too_low, -20001);

v_salary NUMBER := 5000;


BEGIN
-- Code that may raise an error
IF v_salary < 10000 THEN
-- Raise the user-defined exception
RAISE salary_too_low;
END IF;

EXCEPTION
WHEN salary_too_low THEN
DBMS_OUTPUT.PUT_LINE('Custom error: Salary is too low.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred: ' ||
SQLERRM);
END;

Explanation:
●​ PRAGMA EXCEPTION_INIT(salary_too_low, -20001) associates the user-defined exception
salary_too_low with the Oracle error code -20001.
●​ If the salary is less than 10,000, the salary_too_low exception is raised.
●​ In the EXCEPTION block, the salary_too_low exception is caught, and a custom message is
displayed.
Why Use PRAGMA EXCEPTION_INIT?
●​ It allows you to handle Oracle error numbers as user-defined exceptions.
●​ It provides a clean and efficient way to deal with specific errors in your application without
writing repetitive WHEN clauses for common error conditions.
Key Points:
●​ Association: PRAGMA EXCEPTION_INIT links user-defined exceptions to specific Oracle error
numbers.
●​ Flexibility: You can use it to catch and handle Oracle errors that you want to process in a
customized manner, making your exception handling more readable and tailored.

You might also like