Search code examples
pythonexceptionsystemexit

Continue executing a for loop is a specific system exit is raised in Python


I have a function that has multiple sys.exit() exceptions. I am calling the function iteratively and want my loop to continue if a certain sys.exit() is raised while error out for all others. The sample code can be something like:

def exit_sample(test):

        if test == 'continue':
            sys.exit(0)
        else:
            sys.exit("exit")

list = ["continue", "exit", "last"]
for l in list:
        try:
            exit_sample(l)
        except SystemExit:
            print("Exception 0")
            

In the current form, the code will not error out but will print 'Exception 0' every time. I want it to not error out the first time, and then exit when l = "exit". How can that be done?


Solution

  • You can catch the exception, check if it is the one that justifies continue and re-raise it if it does not.

    import sys
    
    def exit_sample(test):
        if test == 'continue':
            sys.exit(0)
        else:
            sys.exit("exit")
    
    lst = ["continue", "exit", "last"]
    for l in lst:
        try:
            exit_sample(l)
        except SystemExit as ex:      # catch the exception to variable
            if str(ex) == "0":        # check if it is one that you want to continue with
                print("Exception 0")
            else:                     # if not re-raise the same exception.
                raise ex