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); begin 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 } try Caption := ListBox1.Items[3] ;{ set form caption to fourth string } except on EStringListError do ShowMessage('List box contains fewer than four strings'); end; end;
void __fastcall TForm1::Button1Click(TObject* Sender) { 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 try Caption = ListBox1->Items->Strings[3] ; // set form caption to 4th string catch (EStringListError &E) 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.
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
|
What do you think about this topic? Send feedback!
|