(Ab)use of Try..Except

Today I found an example of the abuse of a try.. except block.

procedure TMyClass.DoSomething;
var
  sValue: string;
  iValue: Integer;
begin
  ...
  try
    iValue := StrToInt(sValue);
  except
    iValue := 0;
  end;
  ...
end;

The idea is simple. StrToInt converts a string to an integer as long as the string contains an integer value. If not an exception will be raised.
This exception will be caught because of the try..except block and 0 will be assigned to the variable iValue.

Please, never write code like this! The problem is that all kind of exceptions will be caught including EAccessViolation, EOuOfMemory etc..
Certainly is is better to use a function instead of StrToInt that doesn’t throws an exception but allows you to use a default value.

procedure TMyClass.DoSomething;
var
  sValue: string;
  iValue: Integer;
begin
  ...
  iValue := StrToIntDef(sValue, 0);
  ...
end;

If there is no other way, if you have to call a function that possibly raises an exception then catch only this particular exception. In our example we have to catch the EConvertError.

procedure TMyClass.DoSomething;
var
  sValue: string;
  iValue: Integer;
begin
  ...
  try
    iValue := StrToInt(sValue);
  except
    on E: EConvertError do
      iValue := 0;
  end;
  ...
end;
This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.