簡體   English   中英

Python 在“try”塊中引發異常,然后捕獲相同的異常

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

遇到了try / except塊,例如:

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

是否有這樣做的理由,而不是:

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

在您的特定示例中,我也不會使用try / except因為正如您所說,您可以只使用if語句。

Try / except適用於您知道程序可能會崩潰的情況,因此您編寫了一些可以運行的代碼,而不是整個程序崩潰。 例如,您可以使用自定義錯誤消息覆蓋默認錯誤消息。

一個更好的例子可能是您想將用戶寫入的數字乘以 2。 由於input function 總是返回一個string ,我們需要使用內置的int function 將其轉換為一個int 如果用戶輸入了 integer,這將正常工作,但如果用戶輸入了str ,則整個程序將崩潰。 假設如果發生這種情況,我們想打印一條消息,我們可以使用try / except 如果我們還想一遍又一遍地重復這個問題,直到用戶寫一個 integer,我們可以使用一個簡單的while循環。 下面的代碼是這個的實現。

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))

預期結果:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM