How to Raise Exception in PL/SQL?

You can raise an error in PL/SQL using user-defined exception.

Steps to Raise An Exception in PL/SQL

  1. Declare user-defined exception in the declare section of PL/SQL program unit.
  2. Raise it between the program upon some condition.
  3. Handle it in the Exception section of PL/SQL program unit.

Example

SET SERVEROUTPUT ON;
DECLARE
/* first step */
v_error EXCEPTION;

v_total NUMBER;
BEGIN
v_total := 2 + 2;

IF v_total = 4
THEN
/* second step */
RAISE v_error;
END IF;

DBMS_OUTPUT.put_line ('Total is not 4.');
EXCEPTION
WHEN v_error
THEN
/* third step */
DBMS_OUTPUT.put_line ('Error: Total is 4.');
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ('Some error.');
END;
/

Output

Error: Total is 4.
PL/SQL procedure successfully completed.

Reference

User-defined Exception in Oracle

See also:

  1. Create PDF reports in PL/SQL
  2. Raise application error example in PL/SQL
  3. How to create a Procedure inside a package in Oracle
  4. Exception Handling in PL/SQL
Vinish Kapoor
Vinish Kapoor

Vinish Kapoor is a seasoned software development professional and a fervent enthusiast of artificial intelligence (AI). His impressive career spans over 20 years, marked by a relentless pursuit of innovation and excellence in the field of information technology. As an Oracle ACE, Vinish has distinguished himself as a leading expert in Oracle technologies, a title awarded to individuals who have demonstrated their deep commitment, leadership, and expertise in the Oracle community.