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 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

it should be raise exc
@matszwecja Plain raise re-raises the caught exception: docs.python.org/3/tutorial/errors.html#raising-exceptions
Good to know, although I still prefer the explicitness of raise ex.
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")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.