11.2. Program Errors

In a strict sense, a program error is an error made by the user. Sadly, every end user is smart enough to know that he doesn't have to read the user's manual. It's sort of like guys who refuse to ask for directions when they're lost. Users refuse to admit that they don't know how to run a program. As a result, strange things can happen when the program is run.

How can you reduce program errors? The following programming concepts can help.

11.2.1. Data Validation

Perhaps the most common type of program error occurs when the user provides input into the program, but not input of the correct type. For example, the program might request the user to enter the number of units to purchase and the user might mean to type 10, but because of a fat finger types 1o instead. However, a good programmer anticipates such mistakes by adding validation code to a program. If you wish to validate that the user did correctly enter the quantity to be purchased, you can validate the input using the TryParse() method:

bool flag;
int quantity;
flag = int.TryParse(txtQuantity.Text, out quantity);
if (flag == false)          // Things didn't go well
{
      MessageBox.Show("Expected digit characters only. Re-enter.",
                      "Input Error");
      txtQuantity.Focus();
      return;
}

This is a common validation routine you've seen in previous programs.

Invalid input data is probably the most common source of program error. One reason this is true is that you cannot totally control what a user types into a textbox object. ...

Get Beginning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.