Sub topic 5
Reading the Error with SQLCODE and SQLERRM
This chapter assumes that you know basic PL/SQL blocks, exception handlers, and stored procedures. You should also understand that an exception transfers control from the failing statement to a matching WHEN clause.
When an exception occurs, PL/SQL provides two built-in functions for basic diagnostics:
SQLCODEreturns the numeric error code.SQLERRMreturns the error message.
You normally use them inside an exception handler. They describe the exception that caused control to enter that handler.
SQLCODE and SQLERRM in a handler
The following block deliberately divides by zero. The WHEN OTHERS handler reads both diagnostic values.
SET SERVEROUTPUT ON
DECLARE
l_result NUMBER;
BEGIN
SELECT 10 / 0
INTO l_result
FROM dual;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error number: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('Error message: ' || SQLERRM);
END;
/The output includes a negative Oracle error number and a message such as ORA-01476: divisor is equal to zero. The exact message can contain additional text depending on the database version and context.
SQLCODE is useful when a program must record or classify an error. SQLERRM is useful when a person or calling program needs a readable explanation.
| Function | Returns | Typical result |
|---|---|---|
| `SQLCODE` | Numeric error code | `-1476` |
| `SQLERRM` | Error message text | `ORA-01476: divisor is equal to zero` |
Use named handlers before reading diagnostics
Use a specific handler when you know the error type. For example, NO_DATA_FOUND communicates your intent more clearly than WHEN OTHERS.
DECLARE
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(
'No employee was found. Code: ' || SQLCODE
);
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
/The handler can use SQLCODE and SQLERRM even though it names the exception. The named exception should control the program's behavior. The diagnostic functions should provide details for output or logging.
Passing an error number to SQLERRM
SQLERRM can also translate a specified negative Oracle error number into text:
DECLARE
l_message VARCHAR2(200);
BEGIN
l_message := SQLERRM(-2292);
DBMS_OUTPUT.PUT_LINE(l_message);
END;
/This is useful when you already know the error code, but it does not replace exception handling. SQLCODE has no argument and reports the current exception context.
If a handler has finished and no exception is active, SQLCODE normally returns 0, and SQLERRM returns the message for that success state. Therefore, read these functions while handling the exception or copy their values into local variables before calling other routines.
Exercise
Which function should you use to obtain the numeric Oracle error code, and which function returns its text?
Show answer
Use SQLCODE for the numeric code and SQLERRM for the associated error message.