[英]How to continue try block when on exception with keyerror in python
try:
key1 = val1
key2 = val2
key3 = val3
except KeyError:
pass
finally:
createTask()
in the above example, that createTask() runs in loop and keys changes for every run, how to continue to key2 if there is KeyError at key1 for a particular run?在上面的示例中,createTask() 循环运行并且每次运行时键都会更改,如果特定运行的 key1 处存在 KeyError,如何继续到 key2?
Maybe that will do the job:也许这会做的工作:
for key, val in zip([k1, k2, k3], [v1, v2, v3]):
try:
key = val
except KeyError:
pass
finally:
createTask()
Since you simply pass on KeyError, you can use dict
get
to avoid triggering KeyError
.由于您只是传递 KeyError,因此您可以使用
dict
get
来避免触发KeyError
。 Then you will simply have to make sure that createTask()
is smart enough to detect this condition.然后,您只需确保
createTask()
足够聪明,可以检测到这种情况。
key1 = your_dict.get(val1, None)
key2 = your_dict.get(val2, None)
key3 = your_dict.get(val3, None)
createTask()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.