Available CategoriesAdobeMacromediaProgrammingSQLServer AdministrationNetworkingMicrosoft ProductsMac OSLinux systemsMobile devicesXMLCertificationMiscAvailable Tutorials.NET Framework Essentials.NET Programming securityC# In A Nutshell TutorialProgramming C.SharpMastering Visual Studio .NETASP.NETWeb Solutions based on ASP.NET and ADO.NETJava data objectsJava extreme programmingJava performance tuningJava development on pda's. Building applications for pocket pc and palm devicesJavaScript and DHTMLLearning UMLUMLLearning XMLCocoaProgramming CppPerl objects, references and modulesPerl tutorialPython tutorialPython. Text processingPocket pc network programmingPHP & MySQL. Building web database applicationsPHP & MySQL. Programming for beginnersPHP, MySQL and Apache in 24 hoursSoftware architecture in practiceSoftware engineering and computer gamesBuilding Solutions With the Microsoft .NET Compact FrameworkProgramming Microsoft Visual C# 2005ActionscriptMastering Delphi 7Ado.netPractical mod_perlPerl for bioinformaticsWeb ServicesPrinciples of Secure CodingC/C++ Secure ProgrammingASP.NET AJAXVisual C#Borland C++ Builder 6 Developer's Guide |
Logging ErrorsLogging ErrorsMost of the time, you don't know which operation will raise an exception, and you cannot (and should not) wrap each and every piece of code in a try/except block. The general approach is to let Delphi handle all the exceptions and eventually pass them to you, by handling the OnException event of the global Application object. You can do so rather easily with the ApplicationEvents component. In the ErrorLog example, I've added to the main form an instance of the ApplicationEvents component and written a handler for its OnException event:
procedure TFormLog.LogException(Sender: TObject; E: Exception);
var
Filename: string;
LogFile: TextFile;
begin
// prepares log file
Filename := ChangeFileExt (Application.Exename, '.log');
AssignFile (LogFile, Filename);
if FileExists (FileName) then
Append (LogFile) // open existing file
else
Rewrite (LogFile); // create a new one
try
// write to the file and show error
Writeln (LogFile, DateTimeToStr (Now) + ':' + E.Message);
if not CheckBoxSilent.Checked then
Application.ShowException (E);
finally
// close the file
CloseFile (LogFile);
end;
end;
In the global exceptions handler, you can write to the log, for example, the date and time of the event, and also decide whether to show the exception as Delphi usually does (executing the ShowException method of the TApplication class). By default, Delphi executes ShowException only if no OnException handler is installed. In Figure 2.8, you can see the ErrorLog program running and a sample exceptions log open in ConTEXT (a nice programmer's editor built with Delphi and available at www.fixedsys.com/context).
Figure 2.8: The ErrorLog example and the log it produces
|