See All Titles |
![]() ![]() Code ExamplesThis first example returns the square root of a given input value. If the input value is negative or if it is a character, two traceback messages are displayed. Listing 4.1 Square root (File squareroot.py)1: ### 2: # Program: Square root 3: # Author: Andre S Lessa 4: ### 5: 6: ### import modules 7: 8: import sys, traceback, math 9: 10: try: 11: n = float(raw_input("Please, enter a number: ")) 12: print "The sqrt of %f is %f" % (n, math.sqrt(n)) 13: 14: except (ValueError, TypeError, OverflowError): 15: print "-----------------------------------------" 16: print "This is the standard traceback message:" 17: print "" 18: traceback.print_exc() 19: 20: print "-----------------------------------------" 21: print "This is the customized traceback message:" 22: print "" 23: info = sys.exc_info() 24: exc_type = info[0] 25: exc_value = info[1] 26: exc_traceback = info[2] 27: 28: trace = traceback.extract_tb(sys.exc_traceback) 29: print "Exception Type: ", exc_type 30: print "Error Message: ", exc_value 31: print "File name: ", trace[0][0] 32: print "Error message: ", trace[0][1] 33: print "Line: ", trace[0][2] 34: print "Function: ", trace[0][3] 35: else: 36: print "Everything went just fine." The except clause in line 14 covers ValueError, OverflowError, and TypeError exceptions. The else clause in line 35 is only executed when no exception is raised. The next lines show the two traceback messages that are displayed by this program: Python standard traceback message and a customized version. C:\python> s:\python\squareroot.py Please, enter a number: i ----------------------------------------- This is the standard traceback message: Traceback (innermost last): File "s:\python\squareroot.py", line 11, in ? n = float(raw_input("Please, enter a number: ")) ValueError: invalid literal for float(): i ----------------------------------------- This is the customized traceback message: Exception Type: exceptions.ValueError Error Message: invalid literal for float(): i File name: s:\python\squareroot.py Error message: 11 Line: ? Function: n = float(raw_input("Please, enter a number: ")) This example uses multiple except clauses (lines 17 and 20). It also takes advantage of the assert command to raise a debug exception (line 15). Listing 4.2 Internet country codes (File countrycode.py)1: ### 2: # Program: Country code 3: # Author: Andre S Lessa 4: ### 5: 6: ### import modules 7: 8: import sys, string 9: 10: matrix = { "brazil":"br","france":"fr","argentina":"ar","usa":"us"} 11: 12: def getcode(country): 13: try: 14: data = matrix[string.lower(country)] 15: assert data != "br", "You cannot select this country " + } "for this action!" 16: return data 17: except KeyError: 18: print sys.exc_type, ":", "%s is not in the list." % } sys.exc_value 19: print 20: except AssertionError, b: 21: print b 22: print 23: 24: while 1: 25: country = raw_input("Enter the country name or press x to exit: ") 26: if country == "x": 27: break 28: code = getcode(country) 29: if code != None: 30: print "%s's country code is %s" % (country, code) 31: print The following screen dump shows the execution of this program. Note that the program doesn't end after an exception has been raised. C:\>python s:\python\ countrycode.py Enter the country name or press x to exit: Mexico exceptions.KeyError : mexico is not in the list. Enter the country name or press x to exit: USA USA's country code is us Enter the country name or press x to exit: Brazil You cannot select this country for this action! Enter the country name or press x to exit: Argentina Argentina's country code is ar Enter the country name or press x to exit: x C:\Python> See more exception handling cases in the final section of the next chapter.
|
© 2002, O'Reilly & Associates, Inc. |