Skip to main content
 首页 » 编程设计

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

2025年02月15日7落叶无声

这里有一种情况,我有一个主模块,它调用许多子模块,这些子模块又调用子模块及其方法。

例如:

主要模块:

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)”将抛出一个记录到日志文件中的异常,然后我尝试确定错误是否是一个关键错误.如果这是一个严重错误,我想停止执行并关闭所有文件、连接、模块等(基本上是清理)。

通过上面的代码,控制权返回到主模块,执行到下一行。

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

有什么建议可以实现吗?谢谢!

请您参考如下方法:

所以这里最好的方法就是让异常传播到主模块。

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