簡體   English   中英

try/except 沒有捕獲 Python 中的 TypeError

[英]try/except doesn't catch TypeError in Python

我是 Python 的新手,所以如果我的問題很愚蠢,請原諒我,但是,我無法理解下面兩個函數之間的區別以及為什么第二個函數在使用異常時起作用而第一個函數不起作用。 我嘗試將“結果”與“返回”交換,但沒有幫助。 我在想我缺少參數的條件是不正確的,但即使我刪除它並只留下return 'month missing' ,仍然沒有打印異常。

謝謝你的幫助。

def after_n_months(year, month):
    try:
        result year + (month // 12) 
    except TypeError:
        return 'month missing' if month is None else 'year missing' 
print(after_n_months( 2000, ))


def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        return "division by zero!"
print(divide(2,0))

這是因為在您輸入 function 之前捕獲了 TypeError 異常。

試試這個

def after_n_months(year, month):
    return year + (month // 12) 

try : 
    print(after_n_months(2000))
except:
    print("error")

編輯:要測試您的 function,您也可以輸入 None

def after_n_months(year, month):
    try:
        return year + (month // 12) 
    except TypeError:
        return 'month missing' if month is None else 'year missing' 
    print(after_n_months( 2000 ))

print(after_n_months(2000, None))
print(after_n_months(None, 12))

EDIT2:您也可以像這樣將 function 輸入置於 None 中並刪除預期,因為它不需要。

def after_n_months(year = None, month = None):
        if year is None:
            print("Year missing")
            return None
        if month is None:
            print("Month is missing")
            return None
        return year + (month // 12) 

after_n_months(5,12)
after_n_months(year=5)
after_n_months(month=12)

暫無
暫無

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

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