哪个密钥在Python KeyError中失败了?

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,所以不应该使用它.

  • 记录了@QuestionC [`BaseException.args`](https://docs.python.org/3.4/library/exceptions.html#BaseException.args),但没有详细说明其用途是显而易见的. (4认同)
  • 是否建议使用它,因为它没有记录并且参数可能会改变? (4认同)
  • 谢谢.我不认为这有任何记录吗?我在Python文档中找不到它. (2认同)