Python Exception Handling
2003-02-03 13:14:12
Category: python:general
Description: An example on handling errors with try and except.
Author: mind
Viewed: 7947
Rating: (33 votes)


#!/usr/local/bin/python
#
# Errors And Exceptions by mind@metalshell.com
#
# an example on handling errors, with try/except
#
# 03/12/2002
#
# http://www.metalshell.com
#
 
# When errors occur you would normally see something like:
#
# Traceback (most recent call last):
#   File "./errors.py", line 12, in ?
#     x = int(raw_input("Enter a number: "))
# ValueError: invalid literal for int(): a
#
# when an error in your code is caught your program will be
# terminated but if you try and except things you can prevent
# your program from ending by just placing a nice reminder to
# the user to try another option or value..
#
 
 
# the below example shows a good way to catch errors, for example
# we are making x an integer that will store whatever the user enter's
# so if the user entered 'a' obviously it isn't an integer so it
# would produce an error.. So here we are trying to store the user
# input into x as an integer and make an exception for an error..
 
# also our second exception we are going to parse out user termination
# signals such as "Ctrl+C"..
 
while 1:
        try:
                print "Try entering an alphabetic character 'a b..'"
 
                # store the user-input into x as an integer
                x = int(raw_input("Enter a number: "))
 
                # if raw_input() doesn't receive any errors then
                # break the while loop, otherwise.. print error..
                break
 
        except ValueError:
                print
                print "Please enter a valid number [0-9]"
 
 
# in this example i'll show you how you can use try/except to parse
# out keyboard/user related termination signals such as ctrl+c
# the only way to terminate this program is manually kill the process
# or enter the correct information it asks for, other than that the
# while loop will continue on looping..
 
secret="errorsExample"
print "The secret answer is (%s) without brackets, but try to terminate" %(secret)
print "the program by using termination signals like, ctrl+c, ctrl+d, etc.."
 
while 1:
        try:
                q = raw_input("Enter secret answer: ")
                if q == secret:
                        print "You enetered the right secret answer!"
                        break
 
        except KeyboardInterrupt:
                print
                print "Caught ctrl + c"
                pass
 
        except EOFError:
                print
                print "Caught ctrl + d"
                pass