在Python字典中找不到密钥时抛出什么异常?

时间:2010-11-17 18:27:25

标签: python exception dictionary

如果我有:

map = { 'stack':'overflow' }

try:
  map['experts-exchange']
except:                       <--- What is the Exception type that's thrown here?
  print( 'is not free' )

无法在网上找到它。 =(

5 个答案:

答案 0 :(得分:44)

KeyError

如果你在没有try块的情况下在控制台上执行它会告诉你

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

答案 1 :(得分:9)

KeyError

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

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

答案 2 :(得分:4)

它叫做 KeyError

>>d={1:2}

>>d[2]

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

答案 3 :(得分:3)

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'
>>> 

所以猜测可能是...... KeyError

答案 4 :(得分:1)

如果您不知道要处理的特定异常,则可以简单地做这种事情,

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

以上代码的输出是

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

发生异常时,它可能具有关联的值,也称为异常的参数。参数的存在和类型取决于异常类型。

except子句可以在异常名称后指定一个变量。该变量通过存储在instance.args中的参数绑定到异常实例。为方便起见,异常实例定义了__str __(),因此可以直接打印自变量,而不必引用.args。在引发异常之前,可以先实例化异常,然后根据需要向其添加任何属性。