Python定制的异常类应该允许程序在被引发后继续执行

2024-09-30 16:29:32 发布

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

我编写了一个Python程序,它有一个定制的异常类TAException,它工作得很好。 但是一个新的需求迫使我扩展它的功能。如果用户在 程序启动如果引发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

Tags: theruntest程序trueifexceptionmsg