Handling Exceptions in VCL Applications

From RAD Studio
Jump to: navigation, search

Go Up to Exception handling Index

If you use VCL components or the VCL runtime library in your applications, you need to understand the VCL exception handling mechanism. Exceptions are built into many VCL classes and routines and they are thrown automatically when something unexpected occurs. Typically, these exceptions indicate programming errors that would otherwise generate a runtime error. A limited number of these classes is described in VCL Exception Classes.

The mechanics of handling component exceptions are no different than handling any other type of exception.

If you do not handle the exception, VCL handles it in a default manner. Typically, a message displays describing the type of error that occurred. While debugging your application, you can look up the exception class in online Help. The information provided will often help you to determine where the error occurred and its cause.

Certain classes of exceptions do not display an error message when caught by the default handlers. These are described in Silent Exceptions.

A common source of errors in components is range errors in indexed properties. For example, if a list box has three items in its list (0..2) and your application attempts to access item number 3, the list box raises a "List index out of bounds" exception.

The following event handler contains an exception handler to notify the user of invalid index access in a list box:

 procedure TForm1.Button1Click(Sender: TObject);
   ListBox1.Items.Add('a string');{ add a string to list box }
   ListBox1.Items.Add('another string');{ add another string... }
   ListBox1.Items.Add('still another string');{ ...and a third string }
     Caption := ListBox1.Items[3];{ set form caption to fourth string }
     on EStringListError do
       ShowMessage('List box contains fewer than four strings');

If you click the button once, the list box has only three strings, so accessing the fourth string raises an exception. Clicking a second time adds more strings to the list, so it no longer causes the exception.

In addition to handling the exceptions that VCL raises, you can define and raise your own VCL-based exception classes. This is discussed in Defining Your Own VCL Exceptions.

See Also