1
我编写了一个Python程序,该程序具有一个名为TAException的自定义Exception类,它工作正常。 但新的要求迫使我扩展其功能。如果用户在 程序启动时设置了一个特定的标志(-n),程序在引发TAException时不应停止执行。Python自定义异常类应允许在程序执行后继续执行
下面你看我如何试图实现它。在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
只是为了明确它:你不能停止从异常类本身产生的异常。你总是可以实例化一个异常实例('exc = SomeException()')而不用提高它,然后再使用该变量来提高它:'if some condition:raise exc')。异常类是*没有通知*或有机会取消正在执行的'raise'语句。 – 2013-02-15 10:27:20