try..except with empty exceptions

Dave Angel davea at davea.name
Sat Apr 11 04:23:14 CEST 2015


On 04/10/2015 09:42 PM, Steven D'Aprano wrote:
> On Sat, 11 Apr 2015 05:31 am, sohcahtoa82 at gmail.com wrote:
>
>> It isn't document because it is expected.  Why would the exception get
>> caught if you're not writing code to catch it?  If you write a function
>> and pass it a tuple of exceptions to catch, I'm not sure why you would
>> expect it to catch an exception not in the tuple.  Just because the tuple
>> is empty doesn't mean that it should catch *everything* instead.  That
>> would be counter-intuitive.
>
> Really? I have to say, I expected it.
>
>

I'm astounded at your expectation.  That's like saying a for loop on an 
empty list ought to loop on all possible objects in the universe.

The tuple lists those exceptions you're interested in, and they are 
tried, presumably in order, from that collection.  If none of those 
match, then the logic will advance to the next except clause.  If the 
tuple is empty, then clearly none will match.

> try:
>      spam()
> except This, That:
>      # Implicitly a tuple of two exceptions.
>      pass
>
>
> Compare:
>
> try:
>      spam()
> except:
>      # Implicitly an empty tuple.

No, an omitted item is not the same as an empty tuple.  If it were, then 
we wouldn't have the problem of bare excepts, which are so tempting to 
novices.  There's plenty of precedent in many languages for a missing 
item being distinct from anything one could actually supply.

When there's no tuple specified, it's a different syntax, and the 
semantics are specified separately.



-- 
DaveA



More information about the Python-list mailing list