在an answer到my question中有一个小的打字错误。根据答案,我需要处理KeyError,所以我尝试了
def GetInputData(inputdict, attributelist):
result = {}
try:
result = {a: inputdict[v] for a in attributelist}
except KeyError as KE:
print "KeyError", KE
decodeok = False
else:
decodeok = True
finally:
return decodeok, result
这是有效的(在第4行修复错误后。。。[v]
应该是[a]
)。你知道吗
问题是try except finally会导致隐藏未处理的NameError。Try中断到namererror异常的Finally部分,结果decodeok没有初始化。你知道吗
确实,这是由于编码错误造成的,但是我认为没有显式处理的异常仍然应该被引发?这让我头痛不已!我必须一直处理所有可能的异常吗?你知道吗
你不必使用无休止的
你可能想用
或者只是
从documentation:
所以不是
NameError
没有被提升(它将被提升),而是finally
在try:
块离开之前执行。你知道吗无论如何,我建议您这样定义函数:
这样,如果字典中没有属性,用户就可以自己决定是否抛出错误。这就是异常的目的,允许代码的用户决定在出现异常但不是不可预见的情况时应该发生什么。你知道吗
因此,作为这个函数的用户,我可以这样写:
如果我想进行错误检查。你知道吗
相关问题 更多 >
编程相关推荐