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:
No, your code is not equivalent, for several reasons:
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).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.Exception.__context__
attribute, see Python "raise from" usage)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).