本文介绍了使用“例外除外”;与“除外...加薪”在Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些包含类似于以下功能的源代码:

I'm reading some source code which contains a function similar to the following:

def dummy_function():
    try:
        g = 1/0
    except Exception as e:
        raise Exception("There is an error: {}".format(e))

据我了解,所有异常均源自类,因此这应该捕获所有错误。跟随( SystemExit KeyboardInterrupt GeneratorExit );捕获 Exception 会过滤掉您通常希望避免在不重新引发的情况下捕获的那些异常。在较早的Python版本中,它还会捕获字符串异常(不再允许)。

  • 异常除外,因为e 捕获子类,但是然后引发一个新的 Exception()实例;特定的类型信息不能在下游的 try ...中使用,除非语句。

  • 在Python 3中,产生了一个新的来自异常处理程序的异常会创建一个异常链(其中原始异常作为 Exception .__ context __ 属性添加,请参见)

  • 消息已更新;

    • A blank except: catches all exceptions, including those derived from BaseException (SystemExit, KeyboardInterrupt and GeneratorExit); catching Exception filters out those exceptions you generally want to avoid catching without a re-raise. In older Python releases, it would also catch string exceptions (no longer permitted).
    • The except Exception as e catches subclasses, but then raises a new Exception() instance; the specific type information can't be used anymore in downstream try...except statements.
    • In Python 3, raising a new exception from an exception handler creates an exception chain (where the original exception is added as the Exception.__context__ attribute, see Python "raise from" usage)
    • The message is updated; that's probably the whole point here, is to give the exception a different message.

    您发现的代码是很不正确的做法。顶级异常处理程序应该只捕获并打印一条消息,也许还可以追溯一条消息,而不是使用新消息重新引发异常(并且在Python 2中丢失有关原始异常的所有信息,在Python 3中使其无法访问异常)匹配)。

    The code you found is.. rather bad practice. The top-level exception handler should just catch and print a message and perhaps a traceback, rather than re-raise the exception with a new message (and in Python 2 lose all information on the original exception, in Python 3 make it inaccessible to exception matching in later handlers).

    这篇关于使用“例外除外”;与“除外...加薪”在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    10-29 05:27