Professional Documents
Culture Documents
Summary: in this tutorial, you will learn how to handle other unhandled exceptions in the WHEN
OTHER clause using SQLCODE and SQLERRM functions.
EXCEPTION
...
WHEN OTHERS
Because you handle other non-specific exceptions in the WHEN OTHERS clause, you will need to
take advantages of the built-in error functions such as SQLCODE and SQLERRM .
Note that you cannot use SQLCODE or SQLERRM function directly in an SQL statement.
Instead, you must first assign their returned values to variables
(https://www.oracletutorial.com/plsql-tutorial/plsql-variables/) , and then use the variables in the SQL
statement.
SQLCODE function
The SQLCODE function accepts no argument and returns a number code of the most recent
exception.
If the exceptions are internal, SQLCODE returns a negative number except for the NO_DATA_FOUND
exception which has the number code +100.
If the exception is user-defined, SQLCODE returns +1 or the number that you associated with the
exception via the pragma EXCEPTION_INIT .
The SQLCODE is only usable in the exception-handling section. If you use the SQLCODE function
outside an exception handler, it always returns zero.
https://www.oracletutorial.com/plsql-tutorial/oracle-sqlcode/ 1/4
10/17/22, 4:24 PM Handling Other Unhandled Exceptions By Examples
DECLARE
l_code NUMBER;
r_customer customers%rowtype;
BEGIN
EXCEPTION
l_code := SQLCODE;
END;
In this example, we try to fetch too many rows into a record, which results in a error with the
following error code:
Error code:-1422
SQLERRM function
The function SQLERRM takes an argument as an error number and returns the error message
associated with that error number:
SQLERRM([error_number])
In this syntax, the error_number can be any valid Oracle error number.
If you omit the error_number argument, the function will return the error message associated with
the current value of SQLCODE .
Note that the SQLERRM function with no argument is only useful in an exception handler.
This example illustrates how to use the function SQLERRM in an exception handler:
https://www.oracletutorial.com/plsql-tutorial/oracle-sqlcode/ 2/4
10/17/22, 4:24 PM Handling Other Unhandled Exceptions By Examples
DECLARE
l_msg VARCHAR2(255);
r_customer customers%rowtype;
BEGIN
EXCEPTION
l_msg := SQLERRM;
dbms_output.put_line(l_msg);
END;
DECLARE
BEGIN
EXCEPTION
https://www.oracletutorial.com/plsql-tutorial/oracle-sqlcode/ 3/4
10/17/22, 4:24 PM Handling Other Unhandled Exceptions By Examples
DECLARE
BEGIN
CASE l_error
WHEN -1 THEN
-- duplicate email
END CASE;
RAISE;
END;
END;
In this example, the exception handler traps two exceptions -1 (duplicate email ) and -2291 (parent
key not found). It shows a custom message and reraises the exception using the RAISE statement.
In this tutorial, you have learned how to handle other unhandled exceptions in the WHEN OTHER
clause using the SQLCODE and SQLERRM functions.
https://www.oracletutorial.com/plsql-tutorial/oracle-sqlcode/ 4/4