简体   繁体   中英

Python Raising an Exception within "try" block, then catching the same Exception

Came across try / except blocks, such as:

def foo(name):
    try:
        if name == "bad_name":
            raise Exception()
    except Exception:
        do_something()
        return

Is there a reason for doing this, instead of:

def foo(name):
    if name == "bad_name":
        do_something()
        return

In your example specific I would also not have used try / except because as you stated, you could just use an if statement.

Try / except is for occasions where you know the program may crash, so therefore you have written some code that'll run instead of the entire program crashing. You could for example override the default error messages with custom ones.

A better example could be that you want to multiply a number the user wrote times two. Since the input function always returns a string , we need to cast it to an int using the built-in int function. This would work fine if the user had typed in an integer, but if the user had typed in a str instead, the entire program would crash. Let's say we want to print out a message if that happens, we could use try / except . If we also want to repeat the question over and over again until the user writes an integer, we can use a simple while loop. The code below is an implementation of this.

print("Write any integer and I will multiply it with two!")

while True:
    # Get user input
    userInput = input("Write any number: ")
    try:
        # Here we try to cast str to int
        num = int(userInput)

        # The next line will only be run if the line before 
        # didn't crash. We break out of the while loop
        break

    # If the casting didn't work, this code will run
    # Notice that we store the exception as e,
    # so if we want we could print it
    except Exception as e:
        print("{} is not an integer!\n".format(userInput))

# This code will be run if the while loop
# is broken out of, which will only happen
# if the user wrote an integer
print("Your number multiplied with 2:\n{}".format(num * 2))

Expected outcome:

Write any integer and I will multiply it with two!
Write any number: a
a is not an integer!

Write any number: b
b is not an integer!

Write any number: 4
Your number multiplied with 2:
8

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