"请求宽恕比权限更容易#EB;或EAFP,是Python中的常见风格,编码器编写期望错误的代码并使用错误处理进行预期的流量控制
我经常发现的问题是,这可能会导致混淆错误消息。考虑这个例子。
some_dict = {} # oops a bug, this should have 'expected key'
try:
some_dict['optional key'] # expected error
except KeyError:
some_dict['expected key'] # unexpected error
哪个收益率:
Traceback (most recent call last):
File "eafp.py", line 4, in <module>
some_dict['optional key'] # expected error
KeyError: 'optional key'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "eafp.py", line 6, in <module>
some_dict['expected key'] # unexpected error
KeyError: 'expected key'
具体而言,意外错误消息引用了预期的错误消息。这是一个简单的例子,但在某些情况下,第一个错误可能是完全预期的并且不值得注意,但似乎与错误的真正原因密切相关并且可能引起一些混淆。
我的问题是如何最好地处理此类问题。可以抑制第一条错误消息吗?或修改为不那么引人注目的东西?
答案 0 :(得分:0)
对于任何疑惑,我最终使用以下(相当明显的)解决方案在调试时提醒自己。
import logging
logger = logging.getLogger(__name__)
some_dict = {} # oops a bug, this should have 'expected key'
try:
some_dict['optional key'] # expected error
except KeyError as err:
logger.info('Expected Error: %s', err)
some_dict['expected key'] # unexpected error