python - except block 未捕获 ipython 笔记本中的异常

标签 python exception environment

当我在当前的 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/

相关文章:

python - 用 OpenGL 制作太阳系

c# - 是否有与 Java 的 NoSuchElementException 等效的 C#?

windows - 使用批处理文件设置 Windows 环境变量

python - 使用 Python SDK 在 Spark 上运行 Apache Beam wordcount 管道时并行度低

python - 具有一些不可训练权重的自定义 Keras 层

python - 在 numpy 中将同一行堆叠到堆叠二维矩阵的最佳方法是什么?

c++ - 我必须抛出异常吗?

java - 从没有 throws 声明的泛型方法传播异常

jenkins - 如何从 Jenkins 2.0 管道脚本中读取属性文件

php - 检测程序是否通过 HipHop 或常规 CLI/mod_php 运行