除了在ipython笔记本中没有捕获异常的块

时间:2015-08-05 09:29:31

标签: python exception-handling environment

当我在当前的Python环境(ipython notebook cell)中尝试这个简单的例子时,我无法捕获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笔记本中运行相同的复制粘贴代码时,我得到了预期的输出:catched expected error

我知道它与我当前的环境有关,但我不知道从哪里开始寻找!我还尝试了另一个使用AttributeError的示例,在这种情况下,catch块可以工作。

修改 我试过的时候:

   >>> print AttributeError
   <type 'exceptions.AttributeError'>
   >>> print TypeError
   <type 'exceptions.AttributeError'>

我记得在会话的早些时候我犯了一个错误,它重命名为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')

2 个答案:

答案 0 :(得分:3)

我认为可能是某些环境必须隐式导入TypeError:

from exceptions import TypeError

放手一搏!

答案 1 :(得分:0)

此行有错误:

except  AttributeError, TypeError :

这意味着:捕获AttributeError类型的异常,并将该异常分配给名称TypeError。实质上,你这样做了:

except AttributeError as e:
    TypeError = e  # instance of AttributeError!

您可以使用

解决此问题
del TypeError

让Python再次找到内置类型。

更好的解决方案是使用正确的语法:

except (AttributeError, TypeError):

由于这个错误是多么容易,Python 2.6 added the except .. as syntax以及使用except Exception, name:的旧语法已经从Python 3中删除了。

相关问题