开发者

What exception is thrown when key is not found in Python dictionary?

If I have:

map = { 'stack':'overflow' }

t开发者_开发问答ry:
  map['experts-exchange']
except:                       <--- What is the Exception type that's thrown here?
  print( 'is not free' )

Couldn't find it on the web. =(


KeyError

if you do it on the console without the try block will tell it to you

>>> a = {}
>>> a['invalid']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'invalid'
>>> 


KeyError.

>>> x = {'try': 1, 'it': 2}
>>> x['wow']

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    x['wow']
KeyError: 'wow'


Its called KeyError

>>d={1:2}

>>d[2]

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 2


If you don't know the specific exception to handle, you can simply do this kind of thing,

map = {'stack': 'overflow'}

try:
    map['experts-exchange']
except Exception as inst:
    print(type(inst))       # the exception instance
    print(inst.args)        # arguments stored in .args
    print(inst)             # __str__ allows args to be printed directly,
                            # but may be overridden in exception subclasses

The out put of the above code is,

<class 'KeyError'>
('experts-exchange',)
'experts-exchange'

When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type.

The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines __str __() so the arguments can be printed directly without having to reference .args. One may also instantiate an exception first before raising it and add any attributes to it as desired.


Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> map = { 'a' : 'b' }
>>> print map['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> 

So a wild guess might be...a KeyError ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜