Monday, January 16, 2012

2.9. An alternative way to control errors: exceptions

The "classical" way to control errors is using "if" statement to check each possible situation that may lead to error. Modern languages like C#, allow an alternative way, called "exceptions handling".

The idea is: we will "try" to take a few steps, and after all of them, we will detail what must be done in case some step can not be completed. This allows the program to be more readable than the "conventional" alternative, which leads to a series of chained "if" statements.

We will do this by dividing the program fragment in two blocks:

  • In a first block, we write the steps we want to "try".
  • Then we detail the possible exceptions that we want to "catch", and what to do in that case.


We will see in more detail when our programs become more complex programs, especially when we are dealing with files, but we can see a first example, which tries to divide two numbers and catches the possible errors:

/*---------------------------*/
/*  C# Example #26b:         */
/*  example26b.cs            */
/*                           */
/*  Exceptions (1)           */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example26b
{

  public static void Main()
  {
    int number1, number2, result;
      
    try
    {
       Console.WriteLine("Enter first number");
       number1 = Convert.ToInt32( Console.ReadLine() );
      
       Console.WriteLine("Enter second number");
       number2 = Convert.ToInt32( Console.ReadLine() );
      
       result = number1 / number2;
      
       Console.WriteLine("The division is: {0}", result);
    }
    catch (Exception errorFound)
    {
      Console.WriteLine("An error occurred: {0}", errorFound.Message);
    }
  }
 
}

If we enter a text instead of a number, we would get as an answer:

Enter first number
Hola
An error occurred: Input string was not in the correct format

And if the second number is 0, we would get

Enter first number
3
Enter second number
0
An error occurred: Division by zero

(The variable "errorFound" is of type "Exception" and it helps us to access details like about that kind of exception, such as its corresponding message: errorFound.message)

A more elegant alternative is not to "catch" all errors at a time, but one by one (using several "catch" sentences), in order to be able to take different actions, or at least to give more detailed error messages, this way:

/*---------------------------*/
/*  C# Example #26c:         */
/*  example26c.cs            */
/*                           */
/*  Exceptions (2)           */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example26b
{

  public static void Main()
  {
    int number1, number2, result;
      
    try
    {
       Console.WriteLine("Enter first number");
       number1 = Convert.ToInt32( Console.ReadLine() );
      
       Console.WriteLine("Enter second number");
       number2 = Convert.ToInt32( Console.ReadLine() );
      
       result = number1 / number2;
      
       Console.WriteLine("The division is: {0}", result);
    }
    catch (FormatException)
    {
      Console.WriteLine("It's not a valid number");
    }
    catch (DivideByZeroException)
    {
      Console.WriteLine("Can not divide by zero");
    }
  }
 
}

(As seen in this example, if we will not use additional details of the error that has affected the program, we do not need to declare any variable of type Exception.)

Suggested exercises:
Ø     Create a program that asks the user for his age and birth year. If the age entered is not a valid number, it will display a warning message, but still ask for his birth year.

No comments:

Post a Comment