如果它引发一个没有消息的 KeyError,那么它不会打印任何东西。如果你这样做...
try:
connection = manager.connect("I2Cx")
except Exception as e:
print repr(e)
...您至少会获得异常类名称。
更好的选择是使用多个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)
捕获所有异常是有正当理由的,但如果你这样做了,你几乎应该总是重新引发它们......
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
...因为您可能不想处理KeyboardInterrupt
用户按下 CTRL-C 或SystemExit
-blocktry
调用sys.exit()
.