MemoryError的消息为str在Python中为空

Ima*_*ngo 6 python exception-handling exception out-of-memory

这是一个非常愚蠢的问题,但我正在运行一些任务并通过以下方式捕获错误:

try:
    run_something()
except Exception as e:
    handle_error(str(e))
Run Code Online (Sandbox Code Playgroud)

我想将错误消息作为String,因为我正在使用UI,我想在窗口中显示错误.

问题可以复制为:

>>> import numpy as np
>>> np.range(1e10)
MemoryError                               Traceback (most recent call last)
<ipython-input-4-20a59c2069b2> in <module>() 
----> 1 np.arange(1e10)

MemoryError: 
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试捕获错误并打印其消息(我希望它是类似"MemoryError"的东西:

try:
    np.arange(1e10)
except Exception as e:
    print(str(e))
    print("Catched!")
Run Code Online (Sandbox Code Playgroud)

我得到的唯一输出是"Catched!".这是如此愚蠢,我正在做UI和线程的一些工作,并花了我一段时间才意识到问题是一个内存错误,根本没有消息.

MemoryError是唯一被转换为空字符串的异常吗?因为如果是这种情况我可以检查它.如果没有,如何将其消息作为字符串?

Bak*_*riu 5

所以你可能想打印异常类的名称

try:
    np.arange(1e10)
except Exception as e:   #not catch...
    print(str(e.__class__.__name__))
    print("Catched!")
Run Code Online (Sandbox Code Playgroud)

仅使用str(e)打印异常的“消息”,在您的情况下该消息是空的。


请注意,您可以通过属性获取传递给异常构造函数的参数args

In [4]: try:
   ...:     raise ValueError(1,2,3)
   ...: except ValueError as e:
   ...:     print('arguments:', e.args)
arguments: (1, 2, 3)
Run Code Online (Sandbox Code Playgroud)