繁体   English   中英

Python自定义Exception类应该允许在引发程序后继续执行它

[英]Python customized Exception class should allow to continue the program execution after it has been raised

我编写了一个Python程序,它有一个名为TAException的自定义Exception类,它运行正常。 但是一项新要求迫使我扩展其功能。 如果用户在程序启动时设置了特定标志(-n),则程序不应该在引发TAException时停止执行。

下面你看看我是如何尝试实现它的。 在main()中,如果已设置该标志,则会调用TAException.setNoAbort()。 其余的可能是自我解释。 关键是:显然它不起作用。 引发TAException时程序总是中止。 我知道为什么它不起作用,但我不知道如何以不同的方式实现它。 你能告诉我一个优雅的方法吗?

class TAException(Exception):
    _numOfException = 0                                                 # How often has this exception been raised?
    _noAbort = False                                                    # By default we abort the test run if this exception has been raised.

    def __init__(self, TR_Inst, expr, msg):
        '''
        Parameters:
            TR_Inst:    Testreport instance
            expr:       Expression in which the error occured.
            msg:        Explanation for the error.
        '''
        if TR_Inst != None:
            if TAException._noAbort is True:                            # If we abort the test run on the first exception being raised.
                TAException._numOfException += 1                        # Or else only count the exception and continue the test run.
                                                                        # The status of the testreport will be set to "Failed" by TestReportgen.
            else:
                TR_Inst.genreport([expr, msg], False)                   # Generate testreport and exit.

    @staticmethod
    def setNoAbort():
        '''
        Sets TAException._noAbort to True.
        '''
        TAException._noAbort = True

使用参数-n时,程序不应该引发异常,而是使用警告(不会停止程序)。 您可以在此处找到有关警告的更多信息: http//docs.python.org/2/library/warnings.html#module-warnings

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM