Professional Documents
Culture Documents
A user-defined exception must have assigned error_code . To do it, you use the
EXCEPTION_INIT
pragma as follows:
DECLARE
exception_name EXCEPTION;
In this syntax, the error_code is an integer that ranges from -20,999 to -20,000 .
And the message
is a character string with a maximum length of 2,048 bytes.
DECLARE
e_credit_too_high EXCEPTION;
PRAGMA exception_init( e_credit_too_high, -20001 );
l_max_credit customers.credit_limit%TYPE;
l_customer_id customers.customer_id%TYPE := &customer_id;
l_credit customers.credit_limit%TYPE := &credit_limit;
BEGIN
-- get the meax credit limit
SELECT MAX(credit_limit)
INTO l_max_credit
FROM customers;
COMMIT;
In this example,
Here is the output if you enter customer id 100 and credit limit 20000 :
ORA-20001:
If you want to include a custom message, you can replace the line:
And execute the code block again, you will receive the following error:
Typically, the runtime system raises internally defined exceptions implicitly when
they occur. Besides,
you can explicitly raise an internally defined exception with the RAISE statement
if the exception has a
END;
/
RAISE e_credit_too_high;
name:
If you execute the block and enter the customer id -10, you will get the following
error:
You can re-raise the current exception with the RAISE statement. Reraising an
exception passes it to
the enclosing block, which later can be handled further. To reraise an exception,
you don’t need to
specify the exception name.
RAISE exception_name;
DECLARE
l_customer_id customers.customer_id%TYPE := &customer_id;
BEGIN
-- get the meax credit limit
IF l_customer_id < 0 THEN
RAISE invalid_number;
END IF;
END;
/
DECLARE
e_credit_too_high EXCEPTION;
PRAGMA exception_init( e_credit_too_high, -20001 );
l_max_credit customers.credit_limit%TYPE;
l_customer_id customers.customer_id%TYPE := &customer_id;
l_credit customers.credit_limit%TYPE := &credit_limit;
BEGIN
BEGIN
In this example:
First, get the max credit limit from the customers table.
-- get the max credit limit
SELECT MAX(credit_limit)
INTO l_max_credit
FROM customers;
END;
EXCEPTION
WHEN e_credit_too_high THEN
-- get average credit limit
SELECT avg(credit_limit)
into l_credit
from customers;
COMMIT;
END;
/
Second, compare the max credit with the user-input credit. If the user-input credit
is greater than
the max credit, then raise the e_credit_too_high exception.
Third, display a message and reraise the exception in the exception-handling
section in the inner
block.
Finally, in the outer block, reassign the average credit to the l_credit variable
and update the
customer with the newly adjusted credit.
If you enter the customer id 100 and credit limit 10000, the credit limit of the
customer will be updated
to the average credit.
In this tutorial, you have learned how to use the PL/SQL RAISE statement to
explicitly raise a user-
defined exception, internally defined exception, and reraising an exception.