Exception Handling in Python 3

Peter Otten __peter__ at web.de
Sun Oct 24 12:34:00 CEST 2010


Steve Holden wrote:

> On 10/24/2010 1:26 AM, Chris Rebert wrote:
>>> I was somewhat surprised to discover that Python 3 no longer allows an
>>> > exception to be raised in an except clause (or rather that it reports
>>> > it as a separate exception that occurred during the handling of the
>>> > first).
>> <snip>
> [snip]
>>> > What
>>> > is the correct paradigm for this situation?
>> There doesn't seem to be one at the moment, although the issue isn't
>> very serious. Your Traceback is merely being made slightly longer/more
>> complicated than you'd prefer; however, conversely, what if a bug was
>> to be introduced into your exception handler? Then you'd likely very
>> much appreciate the "superfluous" Traceback info.
>> 
>> Your quandary is due to the unresolved status of the "Open Issue:
>> Suppressing Context" in PEP 3141
>> (http://www.python.org/dev/peps/pep-3134/ ). I guess you could start a
>> discussion about closing that issue somehow.
> 
> You're right about the issue not being serious, (and about the possible
> solution, though I don't relish a lengthy discussion on python-dev) but
> it does seem that there ought to be some way to suppress that
> __context__. From the user's point of view the fact that I am raising
> AttributeError because of some implementation detail of __getattr__() is
> exposing *way* too much information.
> 
> I even tried calling sys.exc_clear(), but alas that doesn't help :(

You can install a custom excepthook:

>>> import traceback, sys
>>> from functools import partial
>>> def f():
...     try: 1/0
...     except: raise AttributeError
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 2, in f
ZeroDivisionError: int division or modulo by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in f
AttributeError
>>> sys.excepthook = partial(traceback.print_exception, chain=False)
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in f
AttributeError

Peter




More information about the Python-list mailing list