11 Vote

Delphi: Global treatment of errors (exceptions)

Tutorial by Delphian | 2012-08-15 at 15:20

With the help of Try-Except blocks, Delphi gives us an easy way to catch and handle exceptions. If in the following code an error between "try" and "except" occurs, the code behind the "except" will be executed and we can prevent our application from showing error messages to the user:

   // code
   on E:Exception do begin
     // will be executed when there is an error

However, if you desire a global error handler for all exceptions that occur somewhere in the program, Try-Except quickly reaches its limits. Finally, it would be too cumbersome to write any code of the program into a try-except block. For this reason, I want to show you in this tutorial, how you can catch all errors occuring in your application in a single procedure to handle the exceptions there.

Global Error Treatment

We call our procedure GlobalExceptionHandler and we declare it under "public" in this way:

  procedure GlobalExceptionHandler(Sender: TObject; E: Exception);

Our application knows the event "OnException" that is fired when an exception occurs. We want to overwrite this event with our procedure, so we are using the following code in "OnCreate":

procedure TForm1.FormCreate(Sender: TObject);
  Application.OnException := GlobalExceptionHandler;

Finally, we have to define our procedure GlobalExceptionHandler:

procedure TForm1.GlobalExceptionHandler(Sender: TObject; E: Exception);
  // this code will be executed in the case of an exception

This procedure is called now, whenever an error somewhere in our program encounters. Within the procedure, we can gather more information about the error. In E.ClassName, the type of our exception is written and the error message can be retrieved from E.Message. So, with this, you can define another error handling for each type of error or we can simply write E.ClassName and E.Message to a file and save it.


About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

Delphi: System-Wide HotKey

Tutorial | 1 Comment

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.