Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #38754

Re: Awsome Python - chained exceptions

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Awsome Python - chained exceptions
Date 2013-02-12 10:13 -0500
References <5119de00$0$11096$c3e8da3@news.astraweb.com>
Newsgroups comp.lang.python
Message-ID <mailman.1701.1360682013.2939.python-list@python.org> (permalink)

Show all headers | View raw


On 2/12/2013 1:15 AM, Steven D'Aprano wrote:
> As an antidote to the ill-informed negativity of Ranting Rick's
> illusionary "PyWarts", I thought I'd present a few of Python's more
> awesome features, starting with exception contexts.

You do not need Rick to justify such an informative post.

> If you've ever written an exception handler, you've probably written a
> *buggy* exception handler:
>
>
> def getitem(items, index):
>      # One-based indexing.
>      try:
>          return items[index-1]
>      except IndexError:
>          print ("Item at index %d is missing" % index - 1)  # Oops!
>
>
> Unfortunately, when an exception occurs inside an except or finally
> block, the second exception masks the first, and the reason for the
> original exception is lost:
>
> py> getitem(['one', 'two', 'three'], 5)  # Python 2.6
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "<stdin>", line 6, in getitem
> TypeError: unsupported operand type(s) for -: 'str' and 'int'
>
>
> But never fear! In Python 3.1 and better, Python now shows you the full
> chain of multiple exceptions, and exceptions grow two new special
> attributes: __cause__ and __context__.

Some thought was given to having only one special attribute, but in the 
end it was decided to have __context__ be the actual context and 
__cause__ be the programmer set and displayed 'context'.

> If an exception occurs while handling another exception, Python sets the
> exception's __context__ and displays an extended error message:
>
> py> getitem(['one', 'two', 'three'], 5)  # Python 3.1
> Traceback (most recent call last):
>    File "<stdin>", line 4, in getitem
> IndexError: list index out of range
>
> During handling of the above exception, another exception occurred:
>
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "<stdin>", line 6, in getitem
> TypeError: unsupported operand type(s) for -: 'str' and 'int'
>
> Python 3 also allows you to explicitly set the exception's __cause__
> using "raise...from" syntax:
>
> py> try:
> ...     len(None)
> ... except TypeError as e:
> ...     raise ValueError('bad value') from e
> ...
> Traceback (most recent call last):
>    File "<stdin>", line 2, in <module>
> TypeError: object of type 'NoneType' has no len()
>
> The above exception was the direct cause of the following exception:
>
> Traceback (most recent call last):
>    File "<stdin>", line 4, in <module>
> ValueError: bad value
>
> Note the slight difference in error message. If both __cause__ and
> __context__ are set, the __cause__ takes priority.
>
> Sometimes you actually want to deliberately catch one exception and raise
> another, without showing the first exception. A very common idiom in
> Python 2:
>
> try:
>      do_work()
> except SomeInternalError:
>      raise PublicError(error_message)
>
> Starting with Python 3.3, there is now support from intentionally
> suppressing the __context__:
>
> py> try:
> ...     len(None)
> ... except TypeError:
> ...     raise ValueError('bad value') from None  # Python 3.3
> ...
> Traceback (most recent call last):
>    File "<stdin>", line 4, in <module>
> ValueError: bad value
>
The new features are explained in the Library manual, Ch. 5, Exceptions, 
but without so many clear examples. The 'from None' option has not yet 
been added to the Language reference section on raise statements (an 
issue on the tracker), so it is easy to miss if one does not also read 
the Library chapter.
>
> You can read more about exception chaining here:
>
> http://www.python.org/dev/peps/pep-3134/
> http://www.python.org/dev/peps/pep-0409/

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Awsome Python - chained exceptions Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-12 06:15 +0000
  Re: Awsome Python - chained exceptions Terry Reedy <tjreedy@udel.edu> - 2013-02-12 10:13 -0500
  Re: Awsome Python - chained exceptions Zero Piraeus <schesis@gmail.com> - 2013-02-12 14:01 -0400
    Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-12 19:01 -0800
      Re: Awsome Python - chained exceptions Ian Kelly <ian.g.kelly@gmail.com> - 2013-02-14 00:00 -0700
        Re: Awsome Python - chained exceptions alex23 <wuwei23@gmail.com> - 2013-02-14 16:10 -0800
    Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-12 19:01 -0800
  Re: Awsome Python - chained exceptions Ethan Furman <ethan@stoneleaf.us> - 2013-02-12 10:15 -0800
  Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-12 18:47 -0800
    Re: Awsome Python - chained exceptions Michael Torrie <torriem@gmail.com> - 2013-02-12 21:18 -0700
    Re: Awsome Python - chained exceptions Chris Angelico <rosuav@gmail.com> - 2013-02-13 17:58 +1100
      Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-13 08:14 -0800
        Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-13 08:19 -0800
        Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-13 08:19 -0800
        Re: Awsome Python - chained exceptions Chris Angelico <rosuav@gmail.com> - 2013-02-14 09:10 +1100
          Re: Awsome Python - chained exceptions Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-14 06:39 +0000
            Re: Awsome Python - chained exceptions Serhiy Storchaka <storchaka@gmail.com> - 2013-02-15 20:51 +0200
        Re: Awsome Python - chained exceptions Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-14 13:01 +0100
          Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-14 18:56 -0800
            Re: Awsome Python - chained exceptions Chris Angelico <rosuav@gmail.com> - 2013-02-15 17:18 +1100
              Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-14 23:51 -0800
                Re: Awsome Python - chained exceptions Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-15 10:00 +0100
              Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-14 23:51 -0800
                Re: Awsome Python - chained exceptions alex23 <wuwei23@gmail.com> - 2013-02-17 17:35 -0800
                Re: Awsome Python - chained exceptions Dave Angel <davea@davea.name> - 2013-02-17 20:48 -0500
                Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-17 21:51 -0800
                news.gmane.org (was Re: Awsome Python - chained exceptions Terry Reedy <tjreedy@udel.edu> - 2013-02-18 01:10 -0500
                Re: news.gmane.org (was Re: Awsome Python - chained exceptions rurpy@yahoo.com - 2013-02-18 09:12 -0800
                Re: news.gmane.org (was Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-18 18:32 +0000
                Re: news.gmane.org (was Re: Awsome Python - chained exceptions Terry Reedy <tjreedy@udel.edu> - 2013-02-18 17:45 -0500
                Re: news.gmane.org (was Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-18 06:30 +0000
                Re: news.gmane.org (was Re: Awsome Python - chained exceptions Kwpolska <kwpolska@gmail.com> - 2013-02-18 16:27 +0100
                Re: Awsome Python - chained exceptions alex23 <wuwei23@gmail.com> - 2013-02-18 18:18 -0800
                Re: Awsome Python - chained exceptions rurpy@yahoo.com - 2013-02-19 07:52 -0800
                Re: Awsome Python - chained exceptions rusi <rustompmody@gmail.com> - 2013-02-19 09:14 -0800
                Re: Awsome Python - chained exceptions alex23 <wuwei23@gmail.com> - 2013-02-19 22:57 -0800
                Re: Awsome Python - chained exceptions Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-20 22:50 +1100
                Re: Awsome Python - chained exceptions Rotwang <sg552@hotmail.co.uk> - 2013-02-20 16:00 +0000
                RE: Awsome Python - chained exceptions "J. Marc Edwards" <marc.edwards@nimbisservices.com> - 2013-02-20 11:08 -0500
                Re: Awsome Python - chained exceptions rurpy@yahoo.com - 2013-02-20 08:13 -0800
                Re: Awsome Python - chained exceptions Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-02-20 18:49 -0500
                Re: Awsome Python - chained exceptions Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-02-20 18:47 -0500
      Re: Awsome Python - chained exceptions Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-13 08:14 -0800
    Re: Awsome Python - chained exceptions Michael Torrie <torriem@gmail.com> - 2013-02-13 00:22 -0700

csiph-web