2013-02-15 144 views
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 
+4

只是爲了明確它:你不能停止從異常類本身產生的異常。你總是可以實例化一個異常實例('exc = SomeException()')而不用提高它,然後再使用該變量來提高它:'if some condition:raise exc')。異常類是*沒有通知*或有機會取消正在執行的'raise'語句。 – 2013-02-15 10:27:20

回答