Que*_*onC 47 python python-3.x
如果我抓到了KeyError
,我怎么知道查找失败了?
def poijson2xml(location_node, POI_JSON):
try:
man_json = POI_JSON["FastestMan"]
woman_json = POI_JSON["FastestWoman"]
except KeyError:
# How can I tell what key ("FastestMan" or "FastestWoman") caused the error?
LogErrorMessage ("POIJSON2XML", "Can't find mandatory key in JSON")
Run Code Online (Sandbox Code Playgroud)
Ale*_*ton 72
拿当前的例外(我as e
在这种情况下使用它); 那么KeyError
第一个参数就是引发异常的关键.因此我们可以这样做:
except KeyError as e: # One would do it as 'KeyError, e:' in Python 2.
cause = e.args[0]
Run Code Online (Sandbox Code Playgroud)
这样,您就可以存储违规密钥cause
.
应该注意的是,它e.message
适用于Python 2但不适用于Python 3,所以不应该使用它.
归档时间: |
|
查看次数: |
14344 次 |
最近记录: |