簡體   English   中英

Python函數包裝一些異常代碼

[英]Python function to wrap some exceptions code

我以這種方式在Python中捕獲了兩個異常:

#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.

如果ex1引發異常,那么我想跳過ex2。 如果ex1沒有引發異常,我想嘗試ex2。

最優雅的編碼方式是什么?

我當前的方法是將其包裝在下面的功能塊中,並在正確的位置使用return:

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

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

然后我只在正確的地方調用函數myExceptions(someArgs)

編輯:這將按您描述的那樣工作:

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 :(")

當發生異常時,它會跳過try塊的其余部分,並繼續執行異常...它不會返回。


您正在執行以下操作:

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 :(")

正如Christian所建議的,更好的方法是:

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 :(")

兩者的輸出:

HENRY
Not a dog person
invalid doggo :(

請注意,如果第一行失敗,它將自動跳過第二行,並允許您根據發生的異常來做不同的事情。

我覺得你很困惑。 在上述KeyError之后, except塊之后將繼續執行。 其余的try:被跳過了,這似乎是您想要的:

這就是為什么我可以這樣做:

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

這些印刷品中只有一張會發生。

Python允許您在try/except語句中使用多個exception子句 將來自兩個try塊的所有代碼添加到一個中,然后只需使用兩個else子句即可捕獲兩個潛在的錯誤:

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

這個怎么樣? 但是,在通常情況下,您應該更具體地說明異常,請參見此處: https : //docs.python.org/3/tutorial/errors.html ,例如,將“ except ValueError”僅用於一種錯誤。

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

暫無
暫無

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

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