try..except with empty exceptions

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Fri Apr 10 15:31:58 EDT 2015


On Friday, April 10, 2015 at 1:48:22 AM UTC-7, 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?

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.



More information about the Python-list mailing list