DEV Community

Pranav Bakare
Pranav Bakare

Posted on

PRAGMA EXCEPTION_INIT | keyword in PLSQL | Exceptional Handling

PRAGMA EXCEPTION_INIT is a directive in PL/SQL that serves a specific purpose in exception handling. It is not a function or a procedure but rather a compiler directive that informs the PL/SQL engine to associate a user-defined exception with a specific Oracle error code. Here’s a breakdown of what it is and how it works:

Key Points about PRAGMA EXCEPTION_INIT:

  1. Directive:

PRAGMA is a keyword in PL/SQL used to provide instructions to the compiler. PRAGMA EXCEPTION_INIT is one such directive.

  1. Purpose:

Its primary purpose is to allow developers to define their own exceptions (user-defined exceptions) and map them to specific Oracle error codes. This makes error handling clearer and more manageable.

  1. Syntax:

The general syntax for using PRAGMA EXCEPTION_INIT is:

PRAGMA EXCEPTION_INIT(exception_name, error_number);

exception_name: This is the name of the user-defined exception you want to create.

error_number: This is the specific Oracle error code (e.g., -1476 for "division by zero").

  1. Usage Context:

It is typically used in the declarative section of a PL/SQL block or package, right after defining the user-defined exception.

  1. Example: Here’s a simple example to illustrate its use:

DECLARE
-- Define a user-defined exception
divide_by_zero_exception EXCEPTION;
-- Associate the exception with a specific Oracle error code
PRAGMA EXCEPTION_INIT(divide_by_zero_exception, -1476);
BEGIN
-- Attempt to perform a division
SELECT 10 / 0 INTO v_result FROM dual; -- This will raise a divide by zero error
EXCEPTION
WHEN divide_by_zero_exception THEN
DBMS_OUTPUT.PUT_LINE('Error: Cannot divide by zero.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error Code: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('Error Message: ' || SQLERRM);
END;

  1. Benefits:

Readability: By defining custom exceptions, your code becomes easier to read and maintain.

Specificity: You can handle specific errors in a more targeted manner.

Conclusion

In summary, PRAGMA EXCEPTION_INIT is a powerful tool in PL/SQL that enhances exception handling by linking user-defined exceptions to specific error codes, thus improving the clarity and control of error management in your PL/SQL programs.

Top comments (0)