Scope of Exceptions

Contact Us or call 1-877-932-8228
Scope of Exceptions

Scope of Exceptions

The use of nested blocks will also affect the path of execution when exceptions are raised. When an exception occurs, any exception handler for the block that is associated with the exception will run. If there is no handler for the block, the exception propagates to the enclosing block. If there is no enclosing block, the exception is reported as a runtime error to the calling environment.

Code Sample:

Nested-Blocks/Demos/exception_inner_block_ignored.sql
declare
  x NUMBER;
begin
   
   dbms_output.put_line('In the main block.');
   
   begin
    dbms_output.put_line('In a nested block.');
    
    x := 1/0;
    
    dbms_output.put_line('Still in a nested block.');  
   end;
   
   dbms_output.put_line('At end of the main block.');
   
end;

Code Explanation

In this example, an ORA-01476: divisor is equal to zero is raised and thrown to the outer block. It continues to propagate since it was not handled.

Code Sample:

Nested-Blocks/Demos/exception_outer_block.sql
declare
  x NUMBER;
begin
   
   dbms_output.put_line('In the main block.');
   x := 1/0;  
   dbms_output.put_line('Still in the main block.');
   
   begin
    dbms_output.put_line('In nested block.');
   exception
    when others then
      dbms_output.put_line('Caught an exception');
   end;
   
   dbms_output.put_line('At end of the main block.');
   
end;

Code Explanation

If an exception does occur in an outer block, a subsequent inner block will be skipped (as will any other executable lines of code in the remainder of the outer block prior to the EXCEPTION section). Any exception section in an inner block will not handle an exception raised in an outer block.

Code Sample:

Nested-Blocks/Demos/exception_inner_block_handled.sql
declare
  x NUMBER;
begin
   
   dbms_output.put_line('In the main block.');
   
   begin
    dbms_output.put_line('In a nested block.');
    x := 1/0;  
    
   exception
      when others then
        dbms_output.put_line('caught an exception');
   end;
   
   dbms_output.put_line('At end of the main block.');
   
end;

Code Explanation

An exception handler in an inner block can be used to address exceptions raised within its scope.

Code Sample:

Nested-Blocks/Demos/exception_inner_block_handled_raised.sql
declare
  x NUMBER;
begin
   
   dbms_output.put_line('In the main block.');
   
   begin
    dbms_output.put_line('In a nested block.');
    x := 1/0;  
   exception
      when others then
        dbms_output.put_line('caught an exception');
        raise;
   end;
   
   dbms_output.put_line('At end of the main block.');
   
end;

Code Explanation

If needed, an exception can be handled in an inner block and subsequently re-raised (using the RAISE keyword) to propagate to the outer block.

Next