Error handling in Python: part 2

In the last post, we learned to use an if test to detect an error that could occur when a user runs our program. A more modern and flexible way of handling errors is to try to execute a statement, and if something goes wrong, jump to a specific set of statements to deal with the error, or at least gracefully exit the program.

Try-Except

When using this approach, programs are constructed as follows:

try:
    <statements>
except:
    <statements>

If something goes wrong in the execution of the statements in the try block, Python will raise what is known as an exception. When Python raises an exception the execution of our program jumps to the except block, where statements can provide a remedy for the error.

Try-Except in bmi_calc.py

Below is a version of our bmi_calc.py program that uses the try-except construct.

import sys

try:
    weight = float(sys.argv[1])    # in kg
    height = float(sys.argv[2])    # in meters
except:
    print('This program needs two inputs, weight (kg) and height (m)')
    print('example: python bmi_calc.py 75 1.7')
    sys.exit(1)
bmi = weight/height**2
print(bmi)

If the user forgets to provide weight and height when running our program, sys.argv[1] raises an exception because [1] is an invalid index. Remember that sys.argv[0] is the name of the program, bmi_calc.py in our case, and that sys.argv[1-n] are all subsequent command-line arguments. When an exception is raised, Python immediately jumps and executes the statements found in the except block. In this case, it prints two lines and exits the program.

sys.exit(1). Remember that sys.exit(1) stops the execution of your program. Any numerical value other than zero will cause sys.exit() to stop your program.

If the user provides only one command line argument (height or weight), sys.argv[2] raises an exception because [2] is an invalid index. Let’s give both situations a try:

$ python bmi_calc.py
This program needs two inputs, weight (kg) and height (m)
example: python bmi_calc.py 75 1.7

$ python bmi_calc.py 75
This program needs two inputs, weight (kg) and height (m)
example: python bmi_calc.py 75 1.7

And as before, if we use the program appropriately we get the expected answer:

$ python bmi_calc.py 75 1.7
25.95155709342561

Python executed the statements in the try block and no exceptions were raised, therefore it skips the except block of code and executes the last two lines of our program.

Conclusion

For the user of our program, it does not matter whether we use an if test or a try-except structure. As we will see in the next post, the try-except structure provides more advanced ways of handling errors, which will make our program more clever and informative.

 

Leave a comment