gpt4 book ai didi

python - Python 2.6.5 中的自定义异常处理和导入模块

转载 作者:行者123 更新时间:2023-12-01 06:01:36 25 4
gpt4 key购买 nike

我有一个带有自定义异常类的脚本,其形式为:

class DirectionError(Exception):
pass

我的函数在同一个脚本中,形式如下:

def func1(x):
if x == 1:
raise DirectionError

我将函数调用放入 try/except/except block 中,格式如下:

try:
func1(2)
except DirectionError:
logging.debug("Custom error message")
sys.exit()
except:
logging.debug(traceback.format_exc())

我随后将这些函数移至单独的 mytools.py 文件中。我将 mytools.py 文件导入到我的主 python 脚本中。

我将自定义异常类移至 mytools.py 文件中,但异常未到达主 Python 脚本。

如何获取 mytools.py 文件中的这些函数,以将异常发送回主 Python 脚本中的 try/except block ?

谢谢。

最佳答案

这取决于你如何导入 mytools。如果您将其导入为

import mytools

然后改变:

except DirectionError:

至:

except mytools.DirectionError:

应该可以。

如果您仅导入您的函数:

from mytools import func1

将其更改为:

from mytools import func1, DirectionError

基本上,您需要将 DirectionError 类导入到主代码中并正确引用它。

此外,仅当您调用 func1(1) 并且调用 func1(2) 时才会引发异常。

关于python - Python 2.6.5 中的自定义异常处理和导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10126641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com