Exception Handling: Nested Blocks


Question: Can you use the same name for User-Defined Exceptions in nested blocks?
A: Yes. But, oracle treat them as DIFFERENT exceptions.
If exception e1 is raised and NOT CATCHED in the inner block, it WILL NOT be caught in the outer block EVEN if there is an exception handler with that name.


[ Oracle PL/SQL ]

Case 1: Exception caught in the internal block
set serveroutput on
DECLARE                -- outer block
 e1 exception;
 a integer;
BEGIN
  a :=2; 
  declare              -- inner block
    e1 exception;
    b integer;
  begin
    b := 2;
    raise e1;           -- exception e1 raised.
  exception
    when others then 
       dbms_output.put_line('error1 caught: inner block');
       dbms_output.put_line(sqlerrm);
  end;
  a :=3;
  raise e1;              -- exception e1 raised.
EXCEPTION
 when e1 then 
   dbms_output.put_line('error1 caught: outer block');
END;
/
anonymous block completed
error1 caught: inner block
User-Defined Exception
error1 caught: outer block


Case 2: Exception unhadled in the internal block is NOT caught in the external one
set serveroutput on
DECLARE                         -- outer block
 e1 exception;
 a integer;
BEGIN
  a :=2; 
  declare                -- inner block
    e1 exception;
    b integer;
  begin
    b := 2;
    raise e1;                   -- exception e1 raised
  exception
    when no_data_found then 
       dbms_output.put_line('error1 caught: inner block');
       dbms_output.put_line(sqlerrm);
  end;
  a :=3;
  raise e1;
EXCEPTION
 when e1 then 
   dbms_output.put_line('error1 caught: outer block');
END;
/

Error report:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at line 11
06510. 00000 -  "PL/SQL: unhandled user-defined exception"
*Cause:    A user-defined exception was raised by PL/SQL code, but
           not handled.
*Action:   Fix the problem causing the exception or write an exception
           handler for this condition. Or you may need to contact your
           application administrator or DBA.

No comments:

Post a Comment