Difference between revisions of "2020 - Validation on entering text instead of numerical values"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
Line 1: Line 1:
 +
=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.
 +
 +
=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=
 
<syntaxhighlight lang=csharp>                 
 
<syntaxhighlight lang=csharp>                 
 
while (true)
 
while (true)
Line 14: Line 23:
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
The 'break' will only be reached if the value entered is successfully converted to an integer.

Revision as of 16:24, 10 December 2019

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.

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.