Reputation: 4523
For some reason my code is not catching an exception when I throw it. I have
def trim_rad(rad):
...
if not modrad.shape[0]:
raise IndexError("Couldn't find main chunk")
return modrad, thetas
Then later I call that function:
try:
modrad, thetas = trim_rad(rad)
except IndexError("Couldn't find main chunk"):
return 0
Yet I still get a traceback with that exception. What am I doing wrong?
Upvotes: 8
Views: 32002
Reputation:
You gave except
an instance of an IndexError
. Do this instead:
try:
modrad, thetas = trim_rad(rad)
except IndexError:
print "Couldn't find main chunk"
return 0
Here is an example:
>>> try:
... [1][1]
... except IndexError('no'):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list index out of range
>>> try:
... [1][1]
... except IndexError:
... pass
...
>>>
Upvotes: 11
Reputation: 2013
You seem to be catching the exception wrong. You catch exceptions of type, the notation below will assign the exception to e so you can read the description in your except handler.
try:
modrad, thetas = trim_rad(rad)
except IndexError as e:
print e.message
return 0
Upvotes: 3
Reputation: 2512
change
except IndexError("Couldn't find main chunk"):
to
except IndexError:
Upvotes: 3
Reputation: 34531
Catch just the IndexError
.
try:
raise IndexError('abc')
except IndexError('abc'):
print 'a'
Traceback (most recent call last):
File "<pyshell#22>", line 2, in <module>
raise IndexError('abc')
IndexError: abc
try:
raise IndexError('abc')
except IndexError:
print 'a'
a # Output
So, reduce your code to
try:
modrad, thetas = trim_rad(rad)
except IndexError:
return 0
If you want to catch the error message too, use the following syntax:
try:
raise IndexError('abc')
except IndexError as err:
print err
abc
Upvotes: 14