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.
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
It catches ValueError
s, and assigns the caught exception to the name IndexError
. You want this:
except (ValueError, IndexError):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With