Scope of Exception Handlers

From RAD Studio
Jump to: navigation, search

Go Up to Writing Exception Handlers


You do not need to provide handlers for every kind of exception in every block. You only need handlers for exceptions that you want to handle specially within a particular block.

If a block does not handle a particular exception, execution leaves that block and returns to the block that contains it (or returns to the code that called the block), with the exception still raised. This process repeats with increasingly broad scope until either execution reaches the outermost scope of the application or a block at some level handles the exception.

Thus, you can nest your exception handling code. That is, you can use nested blocks to define local handling for specific exceptions that overrides the handling in the surrounding block. For example:

 try
 { statements }
   try
 { special statements }
   except
     on ESomething do
     begin
 { handling for only the special statements }
     end;
   end;
   { more statements }
 except
   on ESomething do
   begin
     {handling for statements and more statements, but not special statements}
   end;
 end;

Note: This type of nesting is not limited to exception-handling blocks. You can also use it with finally blocks (described in Writing Finally Blocks) or a mix of exception-handling and finally blocks.

See Also