Main Content

Exceptions in Python

Archive - Originally posted on "The Horse's Mouth" - 2005-07-17 10:05:54 - Graham Ellis

Rather than having to check ahead of time for every possible error, Python provides an exception handling capability too. Simply try to perform you action, and define what's to be done in an except block if the action you want can't be completed.

Here's an example in which we (try to) read an integer value from the user. If our user types a value that's not an integer, the exception is caught and the prompt repeated


def gnum(prompt):
while 1:
try:
rv = int(input(prompt+": "))
break
except:
print "eh?"
return rv

first = gnum("First number")
second = gnum("Second number")
print "Sum is "+str(first+second)


By the way - note the use of a named block of code (a function) to avoid the need to repeat code. Good programming practise!