Tuesday, November 09, 2010

Delphi logging by Exception

I had to help a friend out the other day. He is taking over some Delphi application from someone. That someone decided that the Delphi application is too much work. Now this friend of mine warned me that the code was not very good but I did not expect this piece of beautiful code. Beautiful as in, "What the Hell was this guy thinking".

So we start off with this piece of code

procedure TfrmMain.FormCreate(Sender: TObject);
var
 status         : integer ;
 sc_no          : integer ;
 tmpstr         : string;
 cnt            : integer ;
 comms_protocol : integer ;
begin
  Application.OnException := HandleException;
  ...
end;

So this is not bad, we just register on the top level exception handler in the form's constructor. This event handler code looks like this

procedure TfrmMain.HandleException(Sender: TObject; E: Exception);
var
  filename: string;
  logfile : textfile;
begin
  filename := changefileext(application.exename,'.log');
  assignfile(logfile,filename);
  if fileexists (filename) then
    append(logfile)
  else
    rewrite(logfile);
  writeln(logfile,datetimetostr (now)+':'+e.message);
  if cb_debug.checked then
    application.showexception(e);
  closefile(logfile);
end;

Now in this section I would have liked more begin;end; blocks but some people like to make reading code difficult so not too big a problem. Essentially this code just logs the error to a file. So still not bad.

And then the "What the Hell" moment

try
  raise Exception.create('Program Started');
finally
end;

So this guys wants to log that the application started. Instead of refactoring the log procedure to support program logging he just raises an Exception and does nothing with it. Even worse, in Delphi debug mode, Delphi would stop by default, so now you have to switch off the break on exception option in Delphi just to run his application.

So there you have it, how to log messages by using exceptions in an application and please do not try this at home, this guy was a trained professional*

* A trained professional idiot that is.

No comments: