在 Python 中捕获 KeyError [英] Catch KeyError in Python
问题描述
如果我运行代码:
connection = manager.connect("I2Cx")
程序崩溃并报告 KeyError 因为 I2Cx 不存在(应该是 I2C).
The program crashes and reports a KeyError because I2Cx doesn't exist (it should be I2C).
但如果我这样做:
try:
connection = manager.connect("I2Cx")
except Exception, e:
print e
它不会为 e 打印任何内容.我希望能够打印抛出的异常.如果我用除以零操作尝试同样的事情,它会在两种情况下被捕获并正确报告.我在这里错过了什么?
It doesn't print anything for e. I would like to be able to print the exception that was thrown. If I try the same thing with a divide by zero operation it is caught and reported properly in both cases. What am I missing here?
推荐答案
如果它引发了一个没有消息的 KeyError,那么它不会打印任何东西.如果你这样做...
If it's raising a KeyError with no message, then it won't print anything. If you do...
try:
connection = manager.connect("I2Cx")
except Exception as e:
print repr(e)
...你至少会得到异常类名.
...you'll at least get the exception class name.
更好的选择是使用多个 except
块,并且只捕获"您打算处理的异常...
A better alternative is to use multiple except
blocks, and only 'catch' the exceptions you intend to handle...
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)
有正当理由可以捕获所有异常,但如果这样做,您几乎总是应该重新引发它们...
There are valid reasons to catch all exceptions, but you should almost always re-raise them if you do...
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
...因为你可能不想在用户按下 CTRL-C 时处理 KeyboardInterrupt
,也不想在 try
时处理 SystemExit
-block 调用 sys.exit()
.
...because you probably don't want to handle KeyboardInterrupt
if the user presses CTRL-C, nor SystemExit
if the try
-block calls sys.exit()
.
这篇关于在 Python 中捕获 KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!