[Python-Dev] PEP 463: Exception-catching expressions

Eric Snow ericsnowcurrently at gmail.com
Fri Feb 21 17:46:39 CET 2014


On Fri, Feb 21, 2014 at 8:12 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Feb 22, 2014 at 1:50 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:
>> On Sat, 22 Feb 2014 00:28:01 +1000
>> Nick Coghlan <ncoghlan at gmail.com> wrote:
>>>
>>> Neither of these objections addresses the problems with the status quo, though:
>>>
>>> - the status quo encourages overbroad exception handling (as
>>> illustrated by examples in the PEP)
>>
>> I don't get this. Using the proper exception class in a "try...except"
>> suite is no more bothersome than using the proper exception class in
>> this newly-proposed construct.
>
> Overbroad exception handling comes in two ways. One is simply catching
> Exception or BaseException when a narrower class would be better, and
> that's not addressed by this PEP (except insofar as it does not have a
> bare "except:" syntax, and so it forces you to at least be explicit
> about catching BaseException). The other is this:
>
> try:
>     f(x[i])
> except IndexError:
>     f(default)
>
> Translating that into this form:
>
> f(x[i] except IndexError: default)
>
> means that an IndexError thrown inside f() will not be caught. While
> it is, of course, possible to write that currently:
>
> try:
>     arg = x[i]
> except IndexError:
>     arg = default
> f(arg)
>
> it's that much less readable, and as evidenced by several examples in
> the standard library (some of which are in the PEP, and a few more can
> be found in my associated collection [1]), it's common to short-cut
> this. By providing a clean and convenient syntax for catching an
> exception in just one small expression, we encourage the narrowing of
> the catch front.

Be sure to capture in the PEP (within reason) a summary of concerns
and rebuttals/acquiescence.  Eli's, Brett's, and Antoine's concerns
likely reflect what others are thinking as well.  The PEP and its
result will be better for recording such matters.  In fact, that's a
key goal of PEPs. :)

-eric


More information about the Python-Dev mailing list