exc = None
try:
raise Exception
except Exception as exc:
pass
# ...
print(exc)
NameError: name 'exc' is not defined
This used to work in Python2. Why was it changed this way? If I could at least re-assign to exc
, similar to class-level attributes
class Foo(object):
Bar = Bar
but this does not make it work either:
exc = None
try:
raise Exception
except Exception as exc:
exc = exc
Any good hints to achieve the same? I'd prefer not to write something like this:
exc = None
try:
raise Exception("foo")
except Exception as e:
exc = e
# ...
print(exc)
The
try
statement explictily limits the scope of the bound exception, to prevent circular references causing it to leak. See thetry
statement documentation:Emphasis mine; note that your only option is to bind the exception to a new name.
In Python 2, exceptions did not have a reference to the traceback, which is why this was changed.
However, even in Python 2, you are explicitly warned about cleaning up tracebacks, see
sys.exc_info()
:If you do re-bind the exception, you may want to clear the traceback explicitly: