Catch KeyError and AssertionError : except « Statement « Python Tutorial






import sys, string

matrix = {"brazil":"br","france":"fr","argentina":"ar","usa":"us"}

def getcode(country):
     try:
         data = matrix[string.lower(country)]
         assert data != "br", "You cannot select this country for this action!"
         return data
     except KeyError:
   print sys.exc_type, ":", "%s is not in the list." % sys.exc_value
         print
     except AssertionError, b:
         print b
         print

while 1:
    country = raw_input("Enter the country name or press x to exit: ")
    if country == "x":
        break
    code = getcode(country)
    if code != None: 
        print "%s's country code is %s" % (country, code)
        print








3.10.except
3.10.1.Catching Two Exceptions
3.10.2.Simple exception handling example.
3.10.3.Demonstrating exception arguments and stack unwinding.
3.10.4.Catch more than on exceptions
3.10.5.Catch KeyError and AssertionError
3.10.6.try/except block that checks for correct user input
3.10.7.try/except block with string argument