Sub topic 5
Reading the error with SQLCODE and SQLERRM
This chapter assumes you can write an EXCEPTION section with WHEN clauses and have seen WHEN OTHERS. It also assumes you are comfortable with PL/SQL variables and with calling stored procedures. Here you learn what information a handler can read about the current error, what values to expect for each kind of exception, and the mistakes that make that information unreliable.
The two functions
Inside an exception handler, PL/SQL gives you two built-in functions that describe the exception being handled:
SQLCODEreturns the error number as a number.SQLERRMreturns the error message as a string.
They are most useful in a WHEN OTHERS handler, where you do not know in advance which error occurred. A named handler such as WHEN NO_DATA_FOUND already tells you the cause.
DECLARE
l_n NUMBER;
BEGIN
l_n := 1 / 0;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Code: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('Message: ' || SQLERRM);
END;
/With SET SERVEROUTPUT ON, this prints:
Code: -1476
Message: ORA-01476: divisor is equal to zeroThe message is the error number, formatted as ORA- plus five digits, followed by Oracle's text. The code is the same number as a signed integer, so ORA-01476 becomes -1476.
What values to expect
The sign and size of SQLCODE depend on where the exception came from. These rules cover almost every case you will meet.
| Source of the exception | SQLCODE | SQLERRM |
|---|---|---|
| No error (outside a handler, or after success) | 0 | `ORA-0000: normal, successful completion` |
| Most Oracle errors, such as ZERO_DIVIDE | Negative Oracle number, such as -1476 | `ORA-01476: divisor is equal to zero` |
| NO_DATA_FOUND | +100 | `ORA-01403: no data found` |
| User-defined exception with no pragma | +1 | `User-Defined Exception` |
| RAISE_APPLICATION_ERROR(-20001, 'text') | -20001 | `ORA-20001: text` |
| User-defined exception bound with PRAGMA EXCEPTION_INIT | The number you bound | The Oracle message for that number |
Two entries break the "negative number" pattern. NODATAFOUND reports +100 because that is the ANSI SQL value for "no rows", even though the Oracle error is ORA-01403. Every user-defined exception reports +1 unless you bind it to a number, so two different custom exceptions look identical to SQLCODE.
The next block triggers each of those cases and prints the result. The local procedure report takes the values as parameters, which also shows the capture habit described later.
DECLARE
e_custom EXCEPTION;
l_dummy NUMBER;
PROCEDURE report (
p_label IN VARCHAR2,
p_code IN PLS_INTEGER,
p_msg IN VARCHAR2
) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(RPAD(p_label, 14) || p_code || ' | ' || p_msg);
END report;
BEGIN
BEGIN
SELECT employee_id INTO l_dummy
FROM employees
WHERE employee_id = -1;
EXCEPTION
WHEN OTHERS THEN
report('NO_DATA_FOUND', SQLCODE, SQLERRM);
END;
BEGIN
RAISE e_custom;
EXCEPTION
WHEN OTHERS THEN
report('user-defined', SQLCODE, SQLERRM);
END;
BEGIN
RAISE_APPLICATION_ERROR(-20001, 'Bad input');
EXCEPTION
WHEN OTHERS THEN
report('app error', SQLCODE, SQLERRM);
END;
END;
/Expected output:
NO_DATA_FOUND 100 | ORA-01403: no data found
user-defined 1 | User-Defined Exception
app error -20001 | ORA-20001: Bad inputChoosing a path in WHEN OTHERS
SQLCODE lets you branch on a specific error without declaring a named exception for it. This is a legitimate use of WHEN OTHERS, as long as you re-raise everything you do not recognize.
BEGIN
DELETE FROM departments WHERE department_id = 50;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE = -2292 THEN
DBMS_OUTPUT.PUT_LINE('Department still has dependent rows');
ELSE
RAISE;
END IF;
END;
/When you test for a specific error more than once, declare an exception and bind it with PRAGMA EXCEPTION_INIT instead. A named handler is easier to read than a bare number such as -2292. Use the SQLCODE comparison when the test is a one-off, or when the code comes from somewhere you cannot name in a WHEN clause.
Looking up any message with SQLERRM(n)
SQLERRM also accepts an argument. Given an error number, it returns the message for that number, whether or not that error is currently being handled.
BEGIN
DBMS_OUTPUT.PUT_LINE(SQLERRM(-1476));
DBMS_OUTPUT.PUT_LINE(SQLERRM(-1));
DBMS_OUTPUT.PUT_LINE(SQLERRM(100));
DBMS_OUTPUT.PUT_LINE(SQLERRM(0));
END;
/ORA-01476: divisor is equal to zero
ORA-00001: unique constraint (.) violated
ORA-01403: no data found
ORA-0000: normal, successful completionThe argument must be a negative Oracle number, except that 100 and 0 are accepted. Passing a positive number other than 100 does not look up a message. Calling SQLERRM with no argument is the same as SQLERRM(SQLCODE).
The lookup is handy for turning a number stored in a log table back into text. It also means you can look up a message without producing the error.
Rules that cause bugs
Not usable inside SQL
SQLCODE and SQLERRM are PL/SQL functions. You cannot reference them directly in a SQL statement such as an INSERT. This fails to compile with PLS-00231, "function 'SQLERRM' may not be used in SQL":
INSERT INTO my_log (message) VALUES (SQLERRM);Copy the values into local variables first, then use the variables in the statement.
DECLARE
l_code PLS_INTEGER;
l_msg VARCHAR2(512);
BEGIN
UPDATE employees SET salary = salary / 0 WHERE employee_id = 100;
EXCEPTION
WHEN OTHERS THEN
l_code := SQLCODE;
l_msg := SQLERRM;
DBMS_OUTPUT.PUT_LINE('Would log ' || l_code || ': ' || l_msg);
RAISE;
END;
/Capture them first
Make the capture the first statement of the handler. Other statements in the handler can run SQL or call subprograms, and a nested block that handles its own error can replace what the two functions report. A pair of assignments at the top removes that risk.
They only describe the current exception
Outside an exception handler, SQLCODE returns 0 and SQLERRM returns the "normal, successful completion" text. Calling them after the block has finished tells you nothing about an earlier error.
SQLERRM is limited to 512 bytes
The message is truncated at 512 bytes. This matters when an error message embeds long object names or when messages are chained. DBMS_UTILITY.FORMAT_ERROR_STACK returns up to 2000 bytes and is the better tool when you need the whole message. The next chapters cover it alongside the backtrace.
SQLERRM does not say where
Neither function tells you which line failed. A message such as ORA-01476: divisor is equal to zero is the same whether it came from line 3 or line 300. To find the line, you need the backtrace.
Do not hide the error
A handler that only calls SQLERRM and prints it still swallows the exception. The caller sees a successful call and carries on with possibly half-finished work. If the handler cannot fix the problem, finish it with RAISE, as in the SQLCODE = -2292 example above.
Summary of the working model
- Inside a handler,
SQLCODEgives a number andSQLERRMgives text. Both describe the exception that sent control to that handler. - Oracle errors are negative, NODATAFOUND is +100, and an unbound user-defined exception is +1.
- Application errors from
RAISE_APPLICATION_ERRORkeep the number you chose, from -20000 to -20999. SQLERRM(n)looks up any message by number.- Copy both values into variables before using them in SQL, and do it as the handler's first statement.
Exercise
A WHEN OTHERS handler contains the statement INSERT INTO app_log (code, message) VALUES (SQLCODE, SQLERRM); and the procedure will not compile. What is wrong, and how do you fix it?
Show answer
SQLCODE and SQLERRM are PL/SQL functions and cannot be called inside a SQL statement (PLS-00231). Declare variables, for example l_code PLS_INTEGER and l_msg VARCHAR2(512), assign l_code := SQLCODE; and l_msg := SQLERRM; as the first statements in the handler, then use the variables in the INSERT: INSERT INTO app_log (code, message) VALUES (l_code, l_msg);.
Exercise
Two different user-defined exceptions, elowstock and ebadregion, are declared with no PRAGMA EXCEPTION_INIT. A WHEN OTHERS handler logs only SQLCODE. What value does it log for each, and why is that a problem? Name two ways to make them distinguishable.
Show answer
Both log +1, so the log cannot tell them apart. You can give each a distinct number by raising it through RAISEAPPLICATIONERROR with a code in -20000 to -20999, or by binding each exception to a number with PRAGMA EXCEPTIONINIT. You can also add handlers named WHEN elowstock and WHEN ebad_region before WHEN OTHERS.