exceptions

motivation

If you divide by zero, or try to convert something to an integer that can't be converted, your program will crash with an exception:

how old are you? pony         # user enters something silly

Traceback (most recent call last):
  File "exception.py", line 5, in <module>
    age = int(raw_input("how old are you? "))
ValueError: invalid literal for int() with base 10: 'pony'

In the above example, we were doing what we've done all semester, putting a call to raw_input() inside a call to int(). If the user enters something that can't be converted to an integer, our programs crash with the ValueError message.

Wouldn't it be nice to catch that exception, and give the user another chance to enter an integer, instead of just crashing?

syntax

In python, the try/except statement is one way to handle exceptions. The syntax is similar to the if/else statement:

try:
  # do this indented code block
  # could be 1 or more lines
except EXCEPTIONNAME:
  # if there's an error of type EXCEPTIONNAME
  # execute the code block here (and don't crash)

examples

Here's a simple try to get an integer from the user:

age = raw_input("how old are you? ")
try:
  age = int(age)
  print("Your age: %d" % (age))
except ValueError:
  print("That's not an integer!!")

In this example we try to convert the input to an integer. If that fails with a ValueError, we print "That's not an integer!!" and keep going with the rest of the code.

Of course, if the user doesn't give us a valid integer, we should probably ask again. How can we add a while loop to the above, so we keep asking until we get a valid integer?

challenge

Write a function called getInteger(prompt) that presents the user with a prompt, such as "how old are you? " or "Please enter a number from 1-10: ", and gets and returns an integer from the user. Your function should keep asking until it gets a valid integer from the user.

Here's an example of how you might call the function:

def main():
    age = getInteger("how old are you? ")
    print(age)

more info

Here's a list of various python exceptions. For this class, we're just going to use try/except for converting user input to integers and floats, but there are many other possibilities.


CS21 Topics