try..except with empty exceptions

Dave Angel davea at davea.name
Fri Apr 10 16:27:51 EDT 2015


On 04/10/2015 04:48 AM, 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's no more surprising than a for loop over an empty tuple or empty 
list.  There's nothing to do, so you do nothing.



-- 
DaveA



More information about the Python-list mailing list