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

时间:2017-05-19 21:52:48

标签: python python-2.7 python-3.x

这里有一个情况,我有一个主模块,它调用多个子模块,然后调用子模块及其方法。

例如:

主要模块:

import submodule1
import submodule2

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

Submodule1:

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

submodule2:

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

使用上面的代码,控件返回主模块,执行进入下一行。

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

有关如何实现这一目标的任何建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

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

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