RAD Studio
ContentsIndex
PreviousUpNext
Scope of 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;

 

try
{
  // statements
  try
  {
    // special statements
  }
  catch (const ESomething &E)
  {
    // handling for only the special statements;
  }
  // more statements
}
catch (const ESomething &E)
{
  // handling for statements and more statements, but not special statements
}

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.

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!