在Python中捕获KeyError

spi*_*zak 32 python try-catch except

如果我运行代码:

connection = manager.connect("I2Cx")
Run Code Online (Sandbox Code Playgroud)

程序崩溃并报告KeyError,因为I2Cx不存在(它应该是I2C).

但如果我这样做:

try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print e
Run Code Online (Sandbox Code Playgroud)

它没有为e打印任何东西.我希望能够打印抛出的异常.如果我尝试使用除零操作来执行相同操作,则会在两种情况下都正确捕获并报告.我在这里错过了什么?

Aya*_*Aya 57

如果它在没有消息的情况下引发KeyError,那么它将不会打印任何内容.如果你这样做......

try:
    connection = manager.connect("I2Cx")
except Exception as e:
    print repr(e)
Run Code Online (Sandbox Code Playgroud)

...你至少会获得异常类名称.

更好的选择是使用多个except块,并且只"捕获"您打算处理的异常......

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except IndexError as e:
    print 'I got an IndexError - reason "%s"' % str(e)
Run Code Online (Sandbox Code Playgroud)

有正当理由可以捕获所有异常,但如果你这样做,你应该几乎总是重新提升它们......

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except:
    print 'I got another exception, but I should re-raise'
    raise
Run Code Online (Sandbox Code Playgroud)

...因为KeyboardInterrupt如果用户按下CTRL-C,你可能不想处理,也不SystemExittry-block调用sys.exit().


ajp*_*eri 14

我正在使用Python 3.6并在Exception和e之间使用逗号不起作用.我需要使用以下语法(仅适用于任何想知道的人)

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(e.message)
Run Code Online (Sandbox Code Playgroud)


Ric*_*dle 5

您应该查阅抛出异常的任何库的文档,以了解如何从异常中获取错误消息.

或者,调试此类事情的好方法是:

except Exception, e:
    print dir(e)
Run Code Online (Sandbox Code Playgroud)

看看有什么属性e- 你可能会发现它有一个message属性或类似.