309142Lecture Notes 3 -Understanding Exception Handling-1737696975929
309142Lecture Notes 3 -Understanding Exception Handling-1737696975929
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
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.
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.
EXCEPTION
WHEN OTHERS THEN
-- Use SQLCODE to get the error number
DBMS_OUTPUT.PUT_LINE('Error code: ' || SQLCODE);
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:
SQLCODE = -1400 (for NULL SQLERRM = 'ORA-01400: cannot insert NULL into
Example
insertion error) ("EMPLOYEES", "SALARY")'
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.