Defining Protected Blocks

From RAD Studio
Jump to: navigation, search

Go Up to Exception handling Index

To prepare for exceptions, you place statements that might raise them in a try block. If one of these statements does raise an exception, control is transferred to an exception handler that handles that type of exception, then leaves the block. The exception handler is said to catch the exception and specifies the actions to take. By using try blocks and exception handlers, you can move error checking and error handling out of the main flow of your algorithms, resulting in simpler, more readable code.

You start a protected block using the keyword try. The exception handler must immediately follow the try block. It is introduced by the keyword except, and signals the end of the try block. This syntax is illustrated in the following code. If the SetFieldValue method fails and raises an EIntegerRange exception, execution jumps to the exception-handling part, which displays an error message. Execution resumes outside the block.

 try
   SetFieldValue(dataField, userValue);
 except
   on E: EIntegerRange do
     ShowMessage(Format('Expected value between %d and %d, but got %d',
                        E.Min, E.Max, E.Value));
 end;
 { execution resumes here, outside the protected block }

You must have an exception handling block (described in Writing Finally Blocks) immediately after the try block. An exception handling block should include a handler for each exception that the statements in the try block can generate.

See Also