try..except with empty exceptions

Rustom Mody rustompmody at gmail.com
Fri Apr 10 21:56:15 EDT 2015


On Friday, April 10, 2015 at 2:18:22 PM UTC+5:30, Pavel S wrote:
> Hi,
> 
> I noticed interesting behaviour. Since I don't have python3 installation here, I tested that on Python 2.7.
> 
> Well known feature is that try..except block can catch multiple exceptions listed in a tuple:
> 
> 
> exceptions = ( TypeError, ValueError )
> 
> try:
>     a, b = None
> except exceptions, e:
>     print 'Catched error:', e
> 
> 
> However when exceptions=(), then try..except block behaves as no try..except block.
> 
> 
> exceptions = ()
> 
> try:
>     a, b = None   # <--- the error will not be catched
> except exceptions, e:
>     print 'Catched error:', e
> 
> 
> I found use case for it, e.g. when I want to have a method with 'exceptions' argument:
> 
> 
> def catch_exceptions(exceptions=()):
>   try:
>      do_something()
>   except exceptions:
>      do_something_else()
> 
> 
> catch_exceptions()               # catches nothing
> catch_exceptions((TypeError,))   # catches TypeError
> 
> 
> I believe that behaviour is not documented. What you think?

As others have pointed out: "You asked for it; you got it; what's the issue?"

Nevertheless a tentative +1 from me on the suggestions ∵

except :

catches everything 

except ():

catches nothing --- which is brittle to say the least.

Also given this sort of lines in the docs (2.7 tutorial):

-----------------------------
... except (RuntimeError, TypeError, NameError):
...     pass

Note that the parentheses around this tuple are required, because except
ValueError, e: was the syntax used for what is normally written as except
ValueError as e: in modern Python (described below). The old syntax is still 
supported for backwards compatibility. This means except RuntimeError, 
TypeError is not equivalent to except (RuntimeError, TypeError): but to except 
RuntimeError as TypeError: which is not what you want.
------------------------------------

there's already some versioning related brittleness around except.



More information about the Python-list mailing list