【发布时间】:2015-09-07 16:06:42
【问题描述】:
我正在尝试主要从Python's documentation 进行异常处理。我遇到了一个奇怪的问题:目录包含main.py 和exceptions.py。
在exceptions.py(没有导入语句)我定义我的异常类如下:
class ConvergenceError(AssertionError):
def __init__(self,dc_places):
self.decimal_places = dc_places
def __str__(self):
return 'convergence of R_inf is not correct to ', self.decimal_places
在main.py 我有这个导入声明:
import exceptions as ex
我将异常称为如下:
try:
np.testing.assert_array_almost_equal(R_inf,R_itr,4)
raise ex.ConvergenceError(4)
except ex.ConvergenceError as ce :
print str(ce)
我收到以下错误:
except ex.ConvergenceError as ce :
AttributeError: 'module' object has no attribute 'ConvergenceError'
我不明白为什么解释器在exceptions.py 模块中看不到Convergence。
【问题讨论】:
-
print ex.__file__是否给出了您期望的结果?目录中有exceptions.pyc文件吗? -
我不知道 ex.__file__ 做了什么,但是当我运行它时没有任何改变。而且我的目录中没有 exceptions.pyc 文件
-
如果您按照我的建议
print ex.__file__,它将显示ex所指的文件,这可能不是您所期望的。您也可以尝试print dir(ex)查看该模块中定义了哪些属性。 -
print dir(ex) 给了我:['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning'..] 对不起不习惯stackoverflow的格式
-
那么您并没有导入您认为的模块。尝试使用您的自定义异常命名文件(例如
custom_exceptions.py)并从中导入。
标签: python python-2.7 exception-handling