User defined exception handling in Oracle PL/SQL

 To handle errors that are specific to your application or business logic, you can define your own exceptions in PL/SQL. Here's how you can create and handle user-defined exceptions:

  1. Define the Exception: You define custom exceptions using the DECLARE section of a PL/SQL block or package. This is typically done before the BEGIN block.

DECLARE
    my_exception EXCEPTION;
    PRAGMA EXCEPTION_INIT(my_exception, -20001); -- Assign a unique error code

  1. Raise the Exception: When a condition occurs that warrants raising the exception, you use the RAISE statement. You can raise your custom exception along with a custom error message.
IF some_condition THEN RAISE my_exception; END IF;

  1. Handle the Exception: In the EXCEPTION section of your PL/SQL block, you specify how to handle the custom exception.
EXCEPTION WHEN my_exception THEN DBMS_OUTPUT.PUT_LINE('Custom exception occurred.'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);

Here's a complete example:

DECLARE my_exception EXCEPTION; PRAGMA EXCEPTION_INIT(my_exception, -20001); -- Assign a unique error code BEGIN -- Your PL/SQL code here IF some_condition THEN RAISE my_exception; END IF; EXCEPTION WHEN my_exception THEN DBMS_OUTPUT.PUT_LINE('Custom exception occurred.'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM); END;

In this example, if the condition some_condition evaluates to true, the custom exception my_exception is raised. Then, in the EXCEPTION block, the custom exception is caught and handled accordingly. All other exceptions are caught by the WHEN OTHERS clause, which provides a generic error message.

Remember to use meaningful names for your custom exceptions and to document them appropriately for clarity in your code.

Post a Comment

And that's all there is to it!

If anyone has any other questions or requests for future How To posts, you can either ask them in the comments or email me. Please don't feel shy at all!

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

Previous Post Next Post