C# Tutorial - Catching the Exceptions


In application WApp03, if you enter any value other than a whole number, the application will crash. So we are going to edit the application to include some error handling.

Open the Click event handler and change the code to that shown below.

private void button1_Click(object sender, EventArgs e)
{
  int r = 0;
  int a = 0;
  int b = 0;
  bool fail = false;

  try
  {
    a = Convert.ToInt32(this.textBox1.Text);
  }
  catch (Exception ex)
  {
    fail = true;
  }
  
  try
  {
    b = Convert.ToInt32(this.textBox2.Text);
  }
  catch (Exception ex)
  {
    fail = true;
  }

  if( fail == false )
    r = a + b;

  String str = a + " + " + b + " = " + r;

  if (fail == true)
    MessageBox.Show("One of the values entered is not a whole number", "Oops!");
  else
    MessageBox.Show(str, "result");
}

When the contents of each TextBox is validated, any exception that is raised is caught by the program and an appropriate action is taken. In this case, we set the boolean value fail to true. Then if either value is not a whole number, we inform the user.

Now the application will not crash when invalid values have been entered.


<< Previous Contents Next >>

© Publicjoe, 2008