Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I omit the brackets when trying to catch multiple exceptions?

I just tried writing this:

try:
    # do something
except ValueError, IndexError:
    # do something else

And then got very confused when my program still threw an IndexError because I thought I was catching it.

If it doesn't catch the IndexError, what exactly does this code do? It doesn't seem to be a syntax error.

like image 479
mpen Avatar asked Oct 19 '25 16:10

mpen


2 Answers

Because this mistake/problem is so common, the syntax changes for Python3. You code would be equivalent to

try:
    # do something
except (ValueError, ) as IndexError:
    # do something else

You would have seen that this is obviously wrong.

The new syntax works back as far as Python2.6

This works ok

try:
    # do something
except (ValueError, IndexError):
    # do something else

but often you want to do something with the exception, so you can write

try:
    # do something
except (ValueError, IndexError) as e:
    # do something with e
like image 86
John La Rooy Avatar answered Oct 22 '25 07:10

John La Rooy


It catches ValueErrors, and assigns the caught exception to the name IndexError. You want this:

except (ValueError, IndexError):
like image 40
Ignacio Vazquez-Abrams Avatar answered Oct 22 '25 08:10

Ignacio Vazquez-Abrams