我编写了一个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
使用参数-n时,程序不应引发异常,而是使用警告(这不会停止程序)。您可以在此处找到有关警告的更多信息:http://docs.python.org/2/library/warnings.html#module-warnings
相关问题 更多 >
编程相关推荐