[英]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.