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

时间:2014-04-17 16:51:53

标签: 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")

3 个答案:

答案 0 :(得分:62)

获取当前异常(在这种情况下我使用了as e);然后对于KeyError,第一个参数是引发异常的键。因此我们可以做到:

except KeyError as e:  # One would do it as 'KeyError, e:' in Python 2.
    cause = e.args[0]

这样,您就可以将违规密钥存储在cause

应该注意e.message适用于Python 2但不适用于Python 3,所以不应该使用它。

答案 1 :(得分:2)

不确定您是否正在使用任何模块来帮助您 - 如果JSON以dict形式出现,则可以使用dict.get()来实现有用的结束。

def POIJSON2DOM (location_node, POI_JSON):
    man_JSON = POI_JSON.get("FastestMan", 'No Data for fastest man')
    woman_JSON = POI_JSON.get("FastestWoman", 'No Data  for fastest woman')
    #work with the answers as you see fit

dict.get()有两个参数 - 第一个是你想要的key,第二个是在该密钥不存在时返回的值。

答案 2 :(得分:-2)

如果您导入sys模块,则可以使用sys.exc_info()

获取例外信息 像这样:

def POIJSON2DOM (location_node, POI_JSON):
  try:
    man_JSON = POI_JSON["FastestMan"]
    woman_JSON = POI_JSON["FastestWoman"]

  except KeyError:

    # you can inspect these variables for error information
    err_type, err_value, err_traceback = sys.exc_info()

    REDI.LogErrorMessage ("POIJSON2DOM", "Can't find mandatory key in JSON")