Python没有捕获异常

时间:2013-08-15 18:17:55

标签: python

出于某种原因,当我抛出它时,我的代码没有捕获异常。我有

def trim_rad(rad):
    ...

    if not modrad.shape[0]:
        raise IndexError("Couldn't find main chunk")
    return modrad, thetas

然后我称之为该功能:

try:
    modrad, thetas = trim_rad(rad)
except IndexError("Couldn't find main chunk"):
    return 0

然而我仍然得到了一个跟踪异常。我做错了什么?

4 个答案:

答案 0 :(得分:11)

只抓住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

因此,请将代码缩减为

try:
    modrad, thetas = trim_rad(rad)
except IndexError:
    return 0

如果您也想捕获错误消息,请使用以下语法:

try:
    raise IndexError('abc')
except IndexError as err:
    print err


abc

答案 1 :(得分:7)

您向except提供了IndexError的实例。这样做:

try:
    modrad, thetas = trim_rad(rad)
except IndexError:
    print "Couldn't find main chunk"
    return 0

以下是一个例子:

>>> 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
...
>>>

答案 2 :(得分:2)

更改

except IndexError("Couldn't find main chunk"):

except IndexError:

答案 3 :(得分:2)

你好像抓错了。您捕获类型的异常,下面的表示法会将异常分配给e,以便您可以在except处理程序中阅读说明。

try:
    modrad, thetas = trim_rad(rad)
except IndexError as e:
    print e.message
    return 0