Crash Course Delphi, part 5: Validating the inputs


Runtime errors

 
A runtime error occurs when you enter something invalid in one of the input boxes, such as "abc" or "1.2.34".

A runtime error causes an error message that is quite cryptic to the user, after which the program stops. Let's try to avoid this and inform the user that his input was invalid.

Exceptions

When a runtime error occurs, such as an attempt to divide by zero, or an invalid conversion, an exception is "raised" by the program.

To handle this exception, prefix the block of code that you want to monitor for errors with the keyword try. If an exception occurs, the program flow is interrupted.

Further down in the code, the keyword except marks an "exception handling" block of code.

Avoiding illegal conversions

Let's build this technique into our program Foot2Meter:

  1. In foot2metersimp.dpr, change the code for btnFootToMeter's OnClick event handler as follows:
    procedure TForm1.btnFootToMeterClick(Sender: TObject);
    var
      Foot, Meter: real;
      ResultString: string;
    begin
      lblStartUnit.Caption := 'foot';
      try
        Foot := StrToFloat(edInput.Text);
        Meter := Foot * 0.3048;
        ResultString := FormatFloat('0.00', Meter);
        lblResult.Caption := ResultString + ' meter';
      except
        ShowMessage('Invalid number'); 
    end;
  2. Likewise, change the code for btnMeterToFoot:
    procedure TForm1.btnFootToMeterClick(Sender: TObject);
    var
      Foot, Meter: real;
      ResultString: string;
    begin
      lblStartUnit.Caption := 'meter';
      try
        Meter := StrToFloat(edInput.Text);
        Foot := Meter / 0.3048;
        ResultString := FormatFloat('0.00', Foot);
        lblResult.Caption := ResultString + ' foot';
      except
        ShowMessage('Invalid number');
    end;
  3. Compile and test.

Lesson 4 LESSON 4     TOP   LESSON 6 Lesson 6