Use of “except Exception” vs. “except … raise” in Python

前端 未结 1 1311
逝去的感伤
逝去的感伤 2021-01-13 07:53

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:
          


        
1条回答
  •  时光说笑
    2021-01-13 08:43

    No, your code is not equivalent, for several reasons:

    • 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.

    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).

    0 讨论(0)
提交回复
热议问题