当我在当前的 Python 环境(ipython 笔记本单元)中尝试这个简单的示例时,我无法捕获 TypeError 异常:
a = (2,3)
try:
a[0] = 0
except TypeError:
print "catched expected error"
except Exception as ex:
print type(ex), ex
我得到:
<type 'exceptions.TypeError'> 'tuple' object does not support item assignment
当我尝试在同一台计算机上的不同 ipython 笔记本中运行相同的复制粘贴代码时,我得到预期的输出:捕获预期错误
。
我知道这与我当前的环境有关,但我不知道从哪里开始寻找!我还尝试了另一个 AttributeError 示例,在这种情况下 catch block 可以工作。
编辑: 当我尝试时:
>>> print AttributeError
<type 'exceptions.AttributeError'>
>>> print TypeError
<type 'exceptions.AttributeError'>
我记得在 session 早些时候我犯了一个错误,该错误被重命名为 TypeError:
try:
group.apply(np.round, axis=1) #group is a pandas group
except AttributeError, TypeError :
#it should have been except (AttributeError, TypeError)
print ex
这给了我:
('rint', u'occurred at index 54812')
最佳答案
我认为对于某些环境可能必须隐式导入 TypeError:
from exceptions import TypeError
尝试一下!
关于python - except block 未捕获 ipython 笔记本中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31828540/