Free Pascal

Avoiding string to integer conversion errors

When you try to convert a string to an integer, you'll get a runtime error (an "exception") if the conversion fails. Quite annoying for your reputation as a programmer...

But the function TryStrToInt(S, I) comes to the rescue. It tries to convert the string S to an integer. It returns True if the conversion was succesful and parameter I will contain the converted integer. If the conversion failed, i.e. an invalid string, or the value is out of range, then False is returned.

Very useful when you have to convert a string that was entered in a TEdit box:

if not TryStrToInt(Edit1.Text, I) then
  ShowMessage('Invalid number. Please try again')
else begin
  // OK, continue
  // ...