Catch KeyError and AssertionError : except « Statement « Python Tutorial

Home
Python Tutorial
1.Introduction
2.Data Type
3.Statement
4.Operator
5.String
6.Tuple
7.List
8.Dictionary
9.Collections
10.Function
11.Class
12.File
13.Buildin Function
14.Buildin Module
15.Database
16.Regular Expressions
17.Thread
18.Tkinker
19.wxPython
20.XML
21.Network
22.CGI Web
23.Windows
Python Tutorial » Statement » except 




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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.