如果子模块发生异常,如何停止主模块的执行

2024-04-18 18:56:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里,我有一个主模块,它调用许多子模块,这些子模块又调用子模块及其方法。你知道吗

例如:

主模块:

import submodule1
import submodule2

var1=submodule1.test(2,0)
var2=submodule2.verify(2,"zero")

子模块1:

import blah

def test(x,y):
    try:
       return x/y
    except:
       #some code to print the error to log file
       #some code to determine if this is a critical error

子模块2:

import blah

def verify(x,y):
    try:
       return x*y
    except:
       #some code to print the error to log file
       #some code to determine if this is a critical error

现在,在上面的例子中,对方法“submodule1.test(2,0)”的第一次调用将抛出一个记录到日志文件中的异常,然后我尝试确定错误是否严重。如果这是一个严重错误,我想停止执行并关闭所有文件、组件、模块等(基本上是清理)。你知道吗

使用上面的代码,控件返回到主模块,执行继续到下一行。你知道吗

我的主模块可能有许多方法或对象实例化。我不想检查每个语句的条件。你知道吗

对如何实现这一目标有何建议?谢谢您!你知道吗


Tags: 模块to方法testimportreturndefcode
1条回答
网友
1楼 · 发布于 2024-04-18 18:56:44

所以这里最好的方法就是让异常向上传播到主模块。你知道吗

try:
    # Code
except:
    # Print
    if is_critical():
        raise  # This will re-raise the exception you just caught.

相关问题 更多 >