我编写了一个 Python 程序,它有一个名为 TAException 的自定义异常类,它运行良好。但是一个新的需求迫使我扩展它的功能。如果用户在程序启动时设置了特定标志 (-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