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?
When an exception occurs, the Python interpreter stops the current process. It is handled by passing through the calling process. If not, the program will crash. For instance, a Python program has a function X that calls function Y, which in turn calls function Z.
Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
Try and Except Statement – Catching all ExceptionsTry and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.
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
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