Validation and verification using Try - Except in algorithms and programs
Data validation
There are a number of ways a programmer can validate data input in their algorithms and programs.
Many languages have special routines built into them to catch rogue data entry values. These are called 'exceptions'. Python for example, has a number of built-in instructions it can use to look for specific exceptions. For example, you could use one of these to make sure the user enters in only numbers and not letters. If a user enters in a letter when a number was expected, then an 'exception handling routine' is run to deal with the error. The general format for looking for an exception in Python is:
try
do these instructions if there are no exceptions
....
except XXXX
do these instructions if there is a problem with the input
....
Note, however, that there are some variations. Here is an example of it being used. In this program, a number has to be entered. If a letter is entered, then an exception handling routine deals with it.
Using try - except
There are a lot of different types of exception you can look for. You have to look up what is available in whatever language you are using and read the descriptions for them. In Python, you can get a full list in the documentation here. They include ValueError, ZeroDivisionError, TypeError, OverflowError and many more.
You can lots of practice trying out some of the different types of error in our Python course here.