[issue6210] Exception Chaining missing method for suppressing context

Nick Coghlan report at bugs.python.org
Sat Jun 13 03:59:23 CEST 2009


Nick Coghlan <ncoghlan at gmail.com> added the comment:

The current behaviour also doesn't match the spec in PEP 3134, which
states the __context__ attribute will only be set by the VM if it hasn't
already been set.

This is not currently the case, as setting __context__ does not keep the
VM from setting it (I also tried this setting __context__ to 1 - it was
still overridden):

>>> try:
...   1/0
... finally:
...   exc = RuntimeError()
...   exc.__context__ = None
...   raise exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: int division or modulo by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
RuntimeError

The "raise ... from ..." syntax is not the correct syntax to use
however, since that relates the __cause__ atribute rather than __context__.

A better approach may be to provide a "sys.clear_exc_info()" method in
the sys module to allow exceptions to be raised from exception handlers
without any __context__ information.

A somewhat clumsy workaround that will work with current Python 3 is to
defer raising the exception until after the exception handler has
finished execution:

>>> exc = None
>>> try:
...   1/0
... except:
...   exc = RuntimeError()
...
>>> if exc is not None: raise exc
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError

----------
nosy: +ncoghlan

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6210>
_______________________________________


More information about the Python-bugs-list mailing list