0

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?

3 Answers3

2

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
matszwecja
  • 6,357
  • 2
  • 10
  • 17
1

Store the exception in a variable and check if the code (or other characteristics) matches your condition for continuing your code. I modified your code such that it will continue if the exit code is 0 and otherwise re-raises system exit

import sys

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 as exc:
        if exc.code == 0:
            print("continuing")
        else:
            # raise previous exception
            raise
Tzane
  • 2,752
  • 1
  • 10
  • 21
0

What you want is to convert the exception to a string and compare that with "exit". After seeing if it works, you can remove the print statement.

import sys

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 as error:
        print(error)
        if str(error) == "exit":
            sys.exit("foo")
Hai Vu
  • 37,849
  • 11
  • 66
  • 93