2020 - Validation on entering text instead of numerical values

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

The Issue

You will crash the skeleton program if you enter a word or text characters when the program expects an integer.

This will cause an exception, so just having an if statement will not stop this error. The fundamental result of trying to convert non numerical characters into a number will fail.

You can find examples of when this will happen by searching for 'Console.ReadLine()'. You are then looking for when this is inside a 'Convert.ToInt32()'.

The Solution

You need to use exception handling to prevent this. You wrap the code that could crash into a try block, and then after the try block you need to code the catch block. the catch block is only run if an exception happens. Also remember creating an exception will cause the program to jump to the catch block without running any further lines of code in the try.

Example

                
while (true)
{
    Console.Write("Enter X coordinate for new outlet: ");
    try
    {
        x = Convert.ToInt32(Console.ReadLine());
        break;
    }
    catch
    {
         Console.WriteLine("invalid data");
     }
}

The 'break' will only be reached if the value entered is successfully converted to an integer.