PLSQL Eception Handling
PLSQL Eception Handling
Handling
Arshad Madanii
Associate Software Developer
Vibhathi Labs Ind Pvt Ltd
Causes:
Internally defined:
User-defined
Examples:
Syntax:
BEGIN
-- PL/SQL block
EXCEPTION
WHEN exception_name THEN
-- Exception handling code
END;
Example:
BEGIN
SELECT salary INTO v_salary FROM employees WHERE employee_id = 100;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee found with ID 100');
END;
SQLCODE:
Returns the numeric code of the most recent exception.
Syntax: SQLCODE
SQLERRM:
Returns the error message associated with the most recent exception.
Syntax: SQLERRM
Example:
BEGIN
-- Intentional error
SELECT salary INTO v_salary FROM employees WHERE employee_id = -1;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error code: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('Error message: ' || SQLERRM);
END;
Syntax:
PRAGMA EXCEPTION_INIT(exception_name, error_number);
Example:
DECLARE
e_custom EXCEPTION;
PRAGMA EXCEPTION_INIT(e_custom, -20001);
BEGIN
-- Simulate an Oracle error
RAISE_APPLICATION_ERROR(-20001, 'Custom error message');
EXCEPTION
WHEN e_custom THEN
DBMS_OUTPUT.PUT_LINE('Caught custom exception: ' || SQLERRM);
END;
By using this procedure, you can report errors to the callers instead of returning
unhandled exceptions.
Error Number Range: Custom error numbers should fall within the range of -
20000 to -20999.
Error Message Length: The custom error message should not exceed 2048
bytes.
This function formats the current call stack (sequence of procedure calls) as a
string. It's often used in exception handling to log or display the sequence of
procedure calls that led to the current point in the code. This can be very helpful
for debugging and tracing the flow of execution in a PL/SQL program.
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE:
This function formats the error backtrace (sequence of procedure calls) for the
most recent error on the stack. It's often used in exception handling to log or
display the full error stack, including the line numbers and positions of the errors.
Guidelines: