简体   繁体   中英

Python function to wrap some exceptions code

I am catching two exceptions in Python in such way:

#ex1
try: 
    #some code
except:
    #some code to e.g. print str

#ex2
try: 
    #some code
except: 
    #some code to e.g. print str or exit from the program.

if ex1 raises an exception then I want to skip ex2. if ex1 does not raise an exception the I want to try ex2.

What is the most elegant way to code it?

My current approach is to wrap it in a function block as below and use return in right place:

def myExceptions(someArgs):
    #ex1
    try: 
        #some code
    except:
        #some code
        return

    #ex2
    try: 
        #some code
    except: 
        #some code

and then I just call the function in right place myExceptions(someArgs)

EDIT: This will work as you described:

try:
    msg = make_msg_fancy(msg)
    msg = check_for_spam(msg)
except MessageNotFancyException:
    print("couldn't make it fancy :(")
except MessageFullOfSpamException:
    print("too much spam :(")

When an exception occurs, it skips the rest of the try block and continues at the exception... it doesn't go back.


You are doing something like this:

for person in [{"dog": "Henry"}, {}, {"dog": None}]:
    try:
        doggo = person['dog']  # can throw KeyError
    except KeyError:
        print("Not a dog person")
        continue  # skip the rest of the loop (since this is a for loop)

    try:
        print(doggo.upper())  # can throw AttributeError
    except AttributeError:
        print("No doggo :(")

A better way is, as Christian suggested:

for person in [{"dog": "Henry"}, {}, {"dog": None}]:
    try:
        doggo = person['dog']  # can throw KeyError
        print(doggo.upper())  # can throw AttributeError
    except KeyError:  # person dict does not contain a "dog"
        print("Not a dog person")
    except AttributeError:  # dog entry cannot be .upper()'d
        print("invalid doggo :(")

Both of which output:

HENRY
Not a dog person
invalid doggo :(

Note this will skip the second set of lines automatically if the first set fails, and lets you do different things based upon which exception occurred.

I think you're confused. After a KeyError above, execution continues after the except blocks. The rest of the try: is skipped, which is what you seem to want:

That's why I can do:

try:
    dct[key] += value
    print("Added.")
except KeyError:
    dct[key] = value
    print("New key.")

Only one of those prints will happen.

Python allows you to use multiple exception clause in your try/except statements . Add all of your code from the two try blocks into one, and simply use two except clause to catch both potentially errors:

try: 
    #some code
except:
    #some code to e.g. print str
except: 
    #some code to e.g. print str or exit from the program.

How about this? However, in you should usually be more specific with exceptions, see here: https://docs.python.org/3/tutorial/errors.html for example, use "except ValueError" to only except that one type of error.

try:
    # ex1 code
except:
    # handle the exception
else:
    # ex2 code, will only run if there is no exception in ex1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM