[Python-ideas] Bad code exceptions (was PEP-3151 pattern-matching)

Guido van Rossum guido at python.org
Fri Apr 8 19:52:16 CEST 2011


On Fri, Apr 8, 2011 at 10:34 AM, Mike Graham <mikegraham at gmail.com> wrote:
> On Fri, Apr 8, 2011 at 1:11 PM, Guido van Rossum <guido at python.org> wrote:
>> ...
>>
>> - Lastly, there is a bunch of standard exception types that are
>> usually caused by bad code (as opposed to bad data or an environmental
>> problem). This would include NameError, TypeError, AttributeError, but
>> not KeyError, IndexError, ValueError. Perhaps it makes sense to
>> introduce a common base class for these "bad code" exceptions? Unlike
>> the other exception types, I think that the set of "bad code"
>> exceptions is pretty much static; a new library module is not going to
>> define raise a new kind of "bad code" exception. (But it may well
>> define a new kind of "bad data" exception, and I don't think we need a
>> common base class for all "bad data" or "bad state" exceptions.)

> The main usage I see for this is "ignore all exceptions except bad
> programming exceptions". People try to do this now with a bare except
> clause. 97% of the time, doing this is very ill-advised.
>
> My gut reaction is that providing such a thing will encourage people
> to use catchall exceptions. The penalty of making people write
> "(KeyboardInterrupt, NameError, AttributeError)" when they want this
> will be beneficial by a) not further complicating the exception
> hierarchy, b) not encouraging catchalls, and c) making the developer
> decide what they want to ignore and what they want to propagate for
> borderline cases like TypeError.

I'm sorry, but I'm not quite following what you are saying here,
perhaps due to the double negatives you seem to be using. (Or perhaps
because my brain is not working 100% this morning. :-)

Could you elaborate, perhaps with a few examples of good practice, bad
practice, how each would be written with and without the hypothetical
"BadCodeError" exception, and which forms you'd consider good and bad
style?

I could also see how combining this with the 'if' subclause might
actually be beneficial:

try:
  <something highly experimental>
except Exception as e if not isinstance(e, BadCodeError):
  <apparently there was some bad data>

Of course in reality bad data will often lead to a BadCodeError, the
most common example being trying to call a method on a value that is
unexpectedly None. Maybe getattr(None, anything) should raise some
other exception? (Clearly just thinking aloud here. :-)

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list