【问题标题】:Unhandled Exceptions disappear未处理的异常消失
【发布时间】:2014-12-12 18:33:02
【问题描述】:

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 中断了 NameError 异常的 finally 部分,因此 decodeok 没有被初始化。

确实这是由于编码错误,但我认为仍然应该引发未明确处理的异常?这让我头疼不已!我必须一直处理所有可能的异常吗?

【问题讨论】:

  • 也许您应该在 try 块之前初始化 decodeok,就像您对 result 所做的那样,因为通过您的 try 块的代码路径不会初始化它...或者你甚至可以在 try 块中初始化它,紧接在你的 result = ... 行之前...

标签: python exception-handling


【解决方案1】:

来自documentation

finally 子句总是在离开 try 语句之前执行, 是否发生异常。当异常发生时 发生在 try 子句中,并且没有被 except 处理 子句(或出现在 except 或 else 子句中),它是 在 finally 子句执行后重新引发。

所以不是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

如果我想进行错误检查。

【讨论】:

    【解决方案2】:

    你不必使用无穷无尽

    except SomeException:
    

    你可能想使用

    except Exc1, Exc2, ExcN as SomeValue:
    

    或者只是

    except Exception as exc:
    

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 1970-01-01
      • 2013-07-19
      • 2011-11-19
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多