Another important element of database programming is handling database errors in custom ways. Of course, you can let Delphi show an exception message each time a database error occurs, but you might want to try to correct the errors or show more details. You can use three approaches to handle database-related errors:
Wrap a try/except block around risky database operations. This is not possible when the operation is generated by interaction with a data-aware control.
Install a handler for the OnException event of the global Application object.
Handle specific dataset events related to errors, such as OnPostError, OnEditError, OnDeleteError, and OnUpdateError.
Although most of the exception classes in Delphi deliver an error message, database exceptions often include error codes, native SQL server error codes and messages, and the like. The ClientDataSet adds only an error code to its exception class, EDBClient. Showing how to handle it, as I'll do next, will provide you with a guideline for other cases.
As an example, I built a database program that shows the details of the errors in a memo component (errors are automatically generated when the user clicks the program buttons). To handle all the errors, the DBError example installs a handler for the OnException event of the Application global object. The event handler logs some information in a memo showing the details of the database error if it is an EDBClient:
procedure TForm1.ApplicationError (Sender: TObject; E: Exception); begin if E is EDBClient then begin Memo1.Lines.Add('Error: ' + (E.Message)); Memo1.Lines.Add(' Error Code: ' + IntToStr(EDBClient (E).ErrorCode)); end else Memo1.Lines.Add('Generic Error: ' + (E.Message)); end;