Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi. Using try/except throughout the code. Evil?

This is rather theoretical question.

I've encountered this practice in a recent project - almost every procedure and function is wrapped into try/except clause like so:

function TMyClass.DoFoo(aBar: Integer): Boolean;
begin
  try
    .. do something .. // Proper checks for common errors inside
    Result := True;
  except
    LogException(ClassName + '.DoFoo'); // Write exception to log
    Result := False; // Indicate function did not performed what it was asked for
    // Exit without re-raising exception
  end;
end;

procedure TMyClass.Buzz(Sender: TObject);
begin
  try
    .. do something .. // Proper checks for common errors inside
  except
    LogException(ClassName + '.DoFoo'); // Write exception to log
    // Exit without re-raising exception
  end;
end;

This looks like a lot of repetition. However I can see some kind of logic behind it. If you wrap every procedure and function into try..except you would know approximate location of the exception and let the program continue working without popping crash messages at the user, but write them to a log for future analysis.

However this practice is considered to be evil. Why exactly is that?

EDIT:

  • This is a question about project I'm going to work with, I did not invented it myself
  • I'm well aware about madExcept and I use it in other projects
  • Functions and procedures in that project are layed out as usual, there are no signs of procedures being written as functions for sole purpose of replacing exceptions flow
like image 248
Kromster Avatar asked Feb 28 '14 06:02

Kromster


1 Answers

There are all sorts of reasons why this is a simply dreadful idea.

The exception handling is now driving the design of all your functions. They all now need to return booleans. Any real return values have to pass through out parameters. That will destroy the readability of your code and composability of your functions.

And you now need to check the return value of every function call you make and propagate that exception upwards. You've therefore abandoned all the benefits of exception handling. The great thing about exceptions is that you can largely separate normal flow from exceptional flow. With your proposed change, exceptional flow in front and centre.

The other big problem is that you force the code to handle the error as early as possible. But the code at the point where the exception is raised might not be in a position to handle the error. If you let the error float upwards then the code can handle the error at the point where it is able to do so.

If you want the program to log details of an error, and not show a message to the user, that is easy to achieve with exception handling. You can use tools like madExcept, EurekaLog or JclDebug to help make the logging comprehensive.

like image 54
David Heffernan Avatar answered Sep 18 '22 20:09

David Heffernan