Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python not catching exception

Tags:

python

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?

like image 481
ari Avatar asked Aug 15 '13 18:08

ari


People also ask

What happens if an error is not caught in Python?

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.

How do you catch exception errors in Python?

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.

Does exception catch all exceptions Python?

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.

Does catching an exception stop execution Python?

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.


1 Answers

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
like image 188
Sukrit Kalra Avatar answered Nov 10 '22 01:11

Sukrit Kalra