C++ Builder Tutorials

Crash Course C++Builder - part 5: Validating the input


A run time error occurs when you enter something invalid in one of the input boxes, such as "abc" or "1.2.34". A run time error usually shows 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".

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

Further down in the code, the keyword catch 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: (please feel free to add your comments, like we saw earlier!)
    void __fastcall TForm1::btnFootToMeterClick(TObject *Sender)
    {
      float Foot;
      float Meter;
      string ResultString;
      lblStartUnit->Caption = "foot";
      try {
        Foot = StrToFloat(edInput->Text);
        Meter = Foot * 0.3048;
        ResultString = FormatFloat("0.00", Meter);
        lblResult->Caption = ResultString + " meter";
      }
      catch (EConvertError &E) {
        ShowMessage("Invalid number");
      }
    }
  2. Likewise, change the code for btnMeterToFoot:
    void __fastcall TForm1::btnMeterToFootClick(TObject *Sender)
    {
      float Foot;
      float Meter;
      string ResultString;
      lblStartUnit->Caption = "meter";
      try {
        Meter = StrToFloat(edInput->Text);
        Foot = Meter / 0.3048;
        ResultString = FormatFloat("0.00", Foot);
        lblResult->Caption = ResultString + " foot";
      }  
      catch (EConvertError &E) {
        ShowMessage("Invalid number");
      }
    }
  3. Save all, compile and test.


Table of contents

  1. Compiling a Project
  2. Form, Edits, buttons
  3. Properties and events
  4. Event handlers
  5. Validating the input

See also:
   Debugging