📤 Compartilhe este artigo com o link curto:
In mission‑critical enterprise systems, failures in database procedures are inevitable. Whether due to an attempt to insert duplicates in unique keys, violation of integrity constraints, or violated business rules, the way your PL/SQL code handles these exceptions determines the stability of the client application.
By default, Oracle has hundreds of known numeric error codes (such as the famous ORA‑00001 for unique constraint violation or ORA‑02291 for integrity constraint violation). However, handling generic error numbers directly in code makes maintenance and readability difficult. This is where named exceptions and the PRAGMA EXCEPTION_INIT command come into play.
PL/SQL divides exceptions into three main categories:
PRAGMA is a compilation instruction that provides information to the PL/SQL compiler before block execution. By using EXCEPTION_INIT, we associate an Oracle numeric error code with a readable identifier created by us.
Imagine we need to specifically capture the violated foreign key error (ORA‑02291) to return a friendly message to the end user, instead of letting the exception go unhandled:
CREATE OR REPLACE PROCEDURE registrar_pedido ( p_cliente_id IN orders.client_id%TYPE, p_valor IN orders.total_amount%TYPE ) IS -- 1. Declare the custom exception ex_cliente_inexistente EXCEPTION; -- 2. Associate ORA‑02291 code with the exception name via PRAGMA PRAGMA EXCEPTION_INIT(ex_cliente_inexistente, -02291); BEGIN INSERT INTO orders (client_id, total_amount, order_date) VALUES (p_cliente_id, p_valor, SYSDATE); COMMIT; EXCEPTION WHEN ex_cliente_inexistente THEN -- Specific and clean handling for FK violation RAISE_APPLICATION_ERROR(-20001, 'Failed to register order: The informed client ID does not exist in the database.'); WHEN OTHERS THEN -- Generic security catch for unexpected errors RAISE_APPLICATION_ERROR(-20999, 'Unexpected error: ' || SQLERRM); END registrar_pedido;
When we need to validate strictly procedural business rules that are not covered by native database constraints (like checking whether inventory balance is sufficient or whether a credit value is negative), we use the native procedure RAISE_APPLICATION_ERROR.
This function accepts two mandatory parameters:
Mastering advanced exception handling ensures that your database routines are resilient, secure, and easy to maintain in the long term.