RAISE & RAISE_APPLICATION_ERROR 𧨶
Mentor's Note: Oracle handles system errors (like divide by zero). But Oracle doesn't know your business rules. "An order cannot be for 0 items" isn't a database errorβit's a Business Error. You use
RAISEto tell Oracle: "Stop! This is not allowed." π‘
π The Scenario: The Credit Card Check π³¶
Imagine a customer tries to buy a βΉ50,000 laptop. - The SQL is perfect. The database is fine. - The Rule: If "Balance < Price", the purchase must fail. - The Action: You manually "Pull the Alarm" using a custom exception. β
π» 1. The RAISE Statement¶
Used to trigger a pre-defined or user-defined exception.
DECLARE
ex_bad_inventory EXCEPTION;
v_stock NUMBER := 0;
BEGIN
IF v_stock < 1 THEN
RAISE ex_bad_inventory; -- 𧨠Alarm pulled!
END IF;
EXCEPTION
WHEN ex_bad_inventory THEN
DBMS_OUTPUT.PUT_LINE('β οΈ Error: Out of stock!');
END;
π» 2. RAISE_APPLICATION_ERROR π οΈ¶
This is the professional way to communicate with front-end apps (Java, Python, C#). It returns an error code and a message.
- Range: You must use codes between -20000 and -20999.
DECLARE
v_age NUMBER := 10;
BEGIN
IF v_age < 18 THEN
-- π Syntax: (Error_Code, Message)
RAISE_APPLICATION_ERROR(-20001, 'Student must be 18+ to enroll.');
END IF;
END;
π‘οΈ 3. Why use RAISE_APPLICATION_ERROR? (Architect's Note)¶
- Consistency: Your Java app will receive a standard
SQLExceptionwith your specific code and message. - Termination: Unlike a simple
DBMS_OUTPUT, this Stops the code execution immediately. - Rollback: It automatically triggers a ROLLBACK of any uncommitted changes in the current transaction. π
π Comparison¶
| Command | Best For | Result |
|---|---|---|
| RAISE | Internal PL/SQL logic | Jumps to EXCEPTION block |
| RAISE_APP_ERR | Communication with Apps | Jumps to App and shows Error π£ |