多个Try / Except块

时间:2015-06-29 15:21:41

标签: python try-catch

我在程序中有多个try / except块,我正在分析来自另一个模块的字典输入。我基本上使用try / except(EAFP)检查某个键是否在输入中(否则,我想引发错误)。

我想知道是否有更通用的方法。 而不是

try:
    xyz = a['some_key']
except:
    print_error("Key 'some_key' was not defined")

几十次,如果有办法做某事像

try:
    xyz = a['some_key']
    xyz2 = a['some_key2']
    ...
except:
    print_error("The key(s) that were not included were some_key, some_key2")

1 个答案:

答案 0 :(得分:4)

borked_keys = set()
for key in list_of_keys_needed:
    try:
       xyz = a[key]
    except KeyError:
       borked_keys.add(key)

#python3 variant
print("The following keys were missing:", ",".join(borked_keys))
#or, as suggested by jonrsharpe
if borked_keys: raise KeyError(",".join(str(i) for i in borked_keys))

#python 2 variant
print "The following keys were missing: " + ",".join(borked_keys)
#or 
if borked_keys: raise KeyError ",".join(str(i) for i in borked_keys)

#if the keys are already strings, you can just use ",".join(borked_keys).