未处理的异常

2024-09-30 10:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

an answermy 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没有初始化。你知道吗

确实,这是由于编码错误造成的,但是我认为没有显式处理的异常仍然应该被引发?这让我头痛不已!我必须一直处理所有可能的异常吗?你知道吗


Tags: 答案answeranmy错误resultquestiontry
2条回答

你不必使用无休止的

except SomeException:

你可能想用

except Exc1, Exc2, ExcN as SomeValue:

或者只是

except Exception as exc:

documentation

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed.

所以不是NameError没有被提升(它将被提升),而是finallytry:块离开之前执行。你知道吗

无论如何,我建议您这样定义函数:

def get_input_data(input_dict, attributes, check=False):
    """If check is True, raises a KeyError if a key in attributes is not
    in the input dictionary."""
    if check:
        return {a: input_dict[a] for a in attributes}
    else:
        return {a: input_dict[a] for a in input_dict.viewkeys() & attributes}

这样,如果字典中没有属性,用户就可以自己决定是否抛出错误。这就是异常的目的,允许代码的用户决定在出现异常但不是不可预见的情况时应该发生什么。你知道吗

因此,作为这个函数的用户,我可以这样写:

try: 
    get_input_data(input_dict, attributes, check=True)
except KeyError:
    # do what makes sense

如果我想进行错误检查。你知道吗

相关问题 更多 >

    热门问题