Writing the Try Block
Go Up to Defining Protected Blocks
The first part of a protected block is the try block. The try block contains code that can potentially raise an exception. The exception can be raised either directly in the try block, or by code that is called by statements in the try block. That is, if code in a try block calls a routine that doesn't define its own exception handler, then any exceptions raised inside that routine cause execution to pass to the exception-handler associated with the try block. Keep in mind that exceptions don't come just from your code. A call to an RTL routine or another component in your application can also raise an exception.
The following example demonstrates catching an exception thrown from a TFileStream object.
procedure TForm1.Button1Click(Sender: TObject);
var
fileStream: TFileStream;
begin
try
(* Attempt to open a non-existant file *)
fileStream := TFileStream.Create('NOT_THERE.FILE', fmOpenRead);
(* Process the file contents... *)
fileStream.Free;
except
on EFOpenError do ShowMessage('EFOpenError Raised');
else
ShowMessage('Exception Raised');
end;
end;
Using a try block makes your code easier to read. Instead of sprinkling error-handling code throughout your program, you isolate it in exception handlers so that the flow of your algorithms is more obvious.
This is especially true when performing complex calculations involving hundreds of steps, any one of which could fail if one of dozens of inputs were invalid. By using exceptions, you can spell out the normal expression of your algorithm, then provide for those exceptional cases when it doesn't apply. Without exceptions, you have to test every time to make sure you can proceed with each step in the calculation.
For details on raising exceptions from the code in your try block, see Raising an Exception.