Inside Delphi 2006 (Wordware Delphi Developers Library)
The global Application object is responsible for handling exceptions not handled by an exception handling block somewhere in the application. To change the default exception handler, we can use the TApplicationEvents component, found in the Additional category.
The TApplicationEvents component provides the OnException event that fires every time an unhandled exception occurs. The OnException event can be handled with a procedure of TExceptionEvent type. The procedure that handles the OnException event has to accept two parameters: the Sender object and the Exception object.
procedure TMainForm.AppEventsException(Sender: TObject; E: Exception); begin end;
Inside the OnException event handler you can write code that handles the exceptions in a different way than the default handler or you can leave the event handler empty. If you don't want anything to happen when an exception occurs, leave the event handler empty. In this case, you only have to write a comment inside the event handler block to disable the Code Editor's automatic code removal ability.
The OnException event handler can also be used for something more constructive. For instance, you can write code that logs all exceptions and saves them to a text file for later viewing. The following listing shows how to log exceptions inside the OnException event handler.
Listing 13-11: Logging unhandled exceptions
procedure TMainForm.AppEventsException(Sender: TObject; E: Exception); var Log: TextFile; LogFilePath: string; begin LogFilePath := 'c:\exceptions.log'; AssignFile(Log, LogFilePath); try if not FileExists(LogFilePath) then Rewrite(Log) else Append(Log); WriteLn(Log, E.ClassType.ClassName, ' exception occurred with message "', E.Message, '".'); finally CloseFile(Log); end; end;
You can also modify the default exception handler manually (without the TApplicationEvents component) by creating a method that accepts the same parameters as the OnException event and assigning the method to the OnException event of the global Application object.
Listing 13-12: A custom OnException event handler
type TMainForm = class(TForm) private { Private declarations } procedure MyHandler(Sender: TObject; E: Exception); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.MyHandler(Sender: TObject; E: Exception); begin MessageDlg('Do you like the "' + E.Message + '" exception?', mtConfirmation, mbYesNo, 0); end;
After you've created the OnException event handler, you have to assign it to the OnException event of the global Application object.
Listing 13-13: Assigning the event handler to the OnException event
procedure TMainForm.FormCreate(Sender: TObject); begin Application.OnException := MyHandler; end;