Delphi Tutorials »

How to avoid StrToInt errors (exceptions)

The Delphi function StrToInt for string-to-integer conversions generates an exception if the given string does not represent a valid integer. Examples: StrToInt('ABC') or StrToInt('1.5'). That's a nice thing for the automatic validation of user input: if you try to convert an invalid value that was entered, such as into an Edit box, then Delphi automatically displays an error message.

But sometimes you don't want this behaviour, especially when you want to convert several strings into integer numbers, such as the stuff entered in a bunch of Edit boxes, or the strings of a StringGrid, a ListBox,... Then it would be annoying to show an error message for every conversion that goes wrong -- imagine 100 error messages, and each time the user has to click a button to close the dialog window :p

If you use StrToIntDef (string-to-integer-default) instead, you'll never get an exception. If the string is invalid, then this function will return the default value that you provided. Example: StrToIntDef('ABC', 0) returns 0.

Here's a simple source code example, using a TEdit and TLabel components:

The user has to enter the desired amounts of products into several edit boxes. After clicking a button, the amounts are displayed in labels. But if an amount entered is invalid, then act as if 0 was entered:

procedure TForm1.Button1Click(Sender: TObject);
  N: integer;
  N := StrToIntDef(EditApples.Text, 0); // if invalid, result is 0
  LabelApples.Caption := IntToStr(N);

  N := StrToIntDef(EditPears.Text, 0);
  LabelPears.Caption := IntToStr(N);

  N := StrToIntDef(EditOranges.Text, 0);
  LabelOranges.Caption := IntToStr(N);

  // and so on...

Another source code example, this time with a stringgrid:

A stringgrid contains numbers in its first and in its second column, that were collected earlier on from user inputs -- but maybe there are some invalid values.
You want to display the sums of the numbers in the third column. If a string is invalid (such as 'ABC' or '1.5') or if a number is negative, then display the word 'Invalid' :

procedure TForm1.Button1Click(Sender: TObject);
  Row, N1, N2: integer;
  for Row := 0 to StringGrid.RowCount - 1 do begin
    N1 := StrToIntDef(StringGrid1.Cells[0, Row], -1);
    N2 := StrToIntDef(StringGrid.Cells[1, Row], -1);
    if (N1 < 0) or (N2 < 0) then 
      StringGrid1.Cells[3, Row] := IntToStr(N1 + N2)
      StringGrid1.Cells[3, Row] := 'Invalid';

DelphiLand Club Become a member of the DelphiLand Club and get our Crash Course Delphi, plus the fully commented source code of all our tutorial projects, plus guaranteed speedy answers from our Q/A Forum.

TOP    Source Code and Tutorials  Crash Course Delphi  Forum
DelphiLand Club  DC Library Tips  Downloads  Links