Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice to use global exceptions in PL/SQL?

Is it a bad practice to do what the code below does? Will bad things happen to me for writing it?

Edit: this is just an example. I would not use dbms_output for any real error reporting.

CREATE OR REPLACE PACKAGE my_package
AS
PROCEDURE master;
END;
/

CREATE OR REPLACE PACKAGE BODY my_package
AS

my_global_interrupt EXCEPTION;


PROCEDURE my_private_procedure
IS
BEGIN
  -- in case some flag is raised, raise exception to stop process and prepare for resume
  RAISE my_global_interrupt;
END;

PROCEDURE master
IS
BEGIN
  my_private_procedure;
EXCEPTION
  WHEN my_global_interrupt THEN 
    dbms_output.put_line('global interrupt, ');
    -- prepare to resume
END;

END;
/
like image 905
jva Avatar asked Nov 19 '25 09:11

jva


1 Answers

On the contrary globally defined user exceptions is good practice. Consider the following skeleton of a package body.

create or replace package body my_pkg 
as
    my_x1 exception;
    my_x2 exception;
    my_x3 exception;
    PROCEDURE p1 is
    begin
        ...
    exception
        when no_data_found then raise my_x1;
    end p1;
    PROCEDURE p2 is
    begin
        ...
    exception
        when no_data_found then raise my_x2;
    end p2;
    PROCEDURE p3 is
    begin
        ...
    exception
        when no_data_found then raise my_x3;
    end p3;
    PROCEDURE master is
    begin
        p1;
        p2;
        p3;
    exception
        when my_x1 then do_this;
        when my_x2 then do_that;
        when my_x3 then do_the_other;
    end master;
end my_pkg;
/

The use of globally declared exceptions makes exception handling in the master procedure easier.

Also, bear in mind that sometimes we want to propagate the exception beyond the package, to say a program which calls our publicly declared procedure. We can do that by defining our exceptions in the package spec. This means other proecdures can reference them...

SQL> begin
  2      my_pkg.master;
  3  exception
  4      when my_pkg.my_public_x1
  5          then dbms_output.put_line('oh no!');
  6  end;
  7  /
oh no!

PL/SQL procedure successfully completed.

SQL>

We can also associate such exceptions with specific error numbers, so that they are recognisable even if the calling procedure doesn't explicitly handled them.

SQL> exec my_pkg.master
BEGIN my_pkg.master; END;

*
ERROR at line 1:
ORA-20999:
ORA-06512: at "APC.MY_PKG", line 32
ORA-06512: at line 1


SQL>

That's (slightly) more helpful than the generic ORA-06510 error.

like image 113
APC Avatar answered Nov 22 '25 01:11

APC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!