Error handling in Python: part 1
Errors are a part of life. Thus, it makes sense to plan for them and minimize their impact. A computer program that has an unwanted behaviour is said to have a “bug”. These types of errors should be fixed before the code is used and shared with others.
Other types of errors cannot be avoided, but the clever coder can defend herself against such errors by adopting a defensive programming approach.
In a previous post, we created a program called
bmi_calc.py that calculated a person’s BMI based on their weight and height. The user had to input these values as command-line arguments. Here is the program:
import sys weight = float(sys.argv) # in kg height = float(sys.argv) # in meters bmi = weight/height**2 print(bmi)
And here is an example of us using our program:
$ python bmi_calc.py 75 1.75 24.489795918367346
But what if the user forgets to provide their weight and height when they use the function?
$ python bmi_calc.py Traceback (most recent call last): File "bmi_calc.py", line 4, in <module> weight = float(sys.argv) # in kg IndexError: list index out of range
For an experienced Python programmer, this error message will be clear enough to determine what went wrong. But for less experienced programmers or users, it would be good if wrong usage of the program could be detected and correct usage printed. In our case, this would involve verifying whether the user of our function has included two command line arguments (i.e., weight and height) when calling
Here is a revised version of our program:
import sys if not (len(sys.argv) == 3): print('This program needs two inputs, weight (kg) and height (m)') print('example: python bmi_calc.py 75 1.7') sys.exit(1) weight = float(sys.argv) # in kg height = float(sys.argv) # in meters bmi = weight/height**2 print(bmi)
We verify that the user has provided two command line arguments. Remember that the name of the function is considered a command line argument, so there should be a total of three command line arguments:
- weight in kg
- height in m
If the user has not provided three command line arguments, we print an informative message and exit our program using the
sys.exit() function. Any number other than
0 will cause the program to exit.
With this new version of our program, not providing height and weight results in the following output:
$ python bmi_calc.py This program needs two inputs, weight (kg) and height (m) example: python bmi_calc.py 75, 1.7
This is more informative that the previous error message, and helps catch one of the most common errors that can happen with this type of program.
We have learned about defensive programming and error handling. We used an
if test to verify the proper usage of our program. There is, however, a more modern and flexible way of handling errors. This will be the focus of our next post.