1

I wrote a Python programm that has a customized Exception class called TAException and it works fine. But a new requirement forces me to extend its functionaliy. If the user sets a specific flag (-n) on program startup the program should NOT stop execution if TAException is raised.

Below you see how I tried to implement it. In main() TAException.setNoAbort() gets called if that flag has been set. The rest is maybe self-explaining. The point is: Obviously it doesn't work. The program always aborts when TAException is raised. I know why it doesn't work, but I do not know how I can implement it differently. Could you please show me an elegant way to do this?

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
1
  • 4
    Just to make it explicit: You cannot stop an exception being raised from the exception class itself. You can always instanciate an exception instance (exc = SomeException()) without raising it, then later using the variable to raise it anyway: if somecondition: raise exc). The exception class is not informed of or given an opportunity to cancel the raise statement being executed.
    – Martijn Pieters
    Feb 15, 2013 at 10:27

1 Answer 1

4

When using the parameter -n your program should not raise the exception but instead use a warning (that won't stop your program). You can find more info on warning here : http://docs.python.org/2/library/warnings.html#module-warnings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.