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:
try // code except on E:Exception do begin // will be executed when there is an error end; end;
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:
public 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); begin Application.OnException := GlobalExceptionHandler; end;
Finally, we have to define our procedure GlobalExceptionHandler:
procedure TForm1.GlobalExceptionHandler(Sender: TObject; E: Exception); begin // this code will be executed in the case of an exception end;
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
The author has not added a profile short description yet.
Show Profile
Related Topics
Lazarus: Program without GUI - Many WSRegister Errors
Question | 6 Answers
Delphi: System-Wide HotKey
Tutorial | 1 Comment
Delphi: Catching Errors with Try Except is not working
Question | 1 Answer
Create Custom Error Pages for Website
Tip | 0 Comments
Excel Error when opening CSV File: File was detected as SYLK File!
Question | 1 Answer
XAMPP: How to set up SSL/HTTPS for local Projects
Tutorial | 0 Comments
Android Programming: Send data via HTTP POST request
Tutorial | 0 Comments
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.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.