Exception handling

You will have noticed that when something goes wrong in a Python program you see an error message. This is called an exception, and you can handle them explicitly to prevent your program from aborting and printing an unhelpful traceback.

For example, take the following code that asks the user to enter an integer, then prints "Hello" that number of times:


In [1]:
n = int(input("Enter an integer: "))
print("Hello " * n)


Enter an integer: two
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-c34b9ba63598> in <module>()
----> 1 n = int(input("Enter an integer: "))
      2 print("Hello " * n)

ValueError: invalid literal for int() with base 10: 'two'

This failed when we provided input that could not be converted to an integer.

We can re-write this so that we catch the exception before it gets to the user, and print a helpful message instead:


In [2]:
try:
    n = int(input("Enter an integer: "))
    print("Hello " * n)
except ValueError:
    print("That wasn't an integer!")


Enter an integer: blah
That wasn't an integer!

You can handle errors in anyway that might be appropriate for your program.

We could take this one step further by continually asking the user for input until we get an integer:


In [3]:
while True:
    try:
        n = int(input("Enter an integer: "))
        print("Hello " * n)
        break
    except ValueError:
        print("That wasn't an integer! Try again...")
    except KeyboardInterrupt:
        print('bye')
        break


Enter an integer: two
That wasn't an integer! Try again...
Enter an integer: blah
That wasn't an integer! Try again...
Enter an integer: 2
Hello Hello