2 回答

TA貢獻2036條經驗 獲得超8個贊
在極少數(shù)情況下, atry: / except:
確實是合適的做法。顯然,您給出的示例是抽象的,但在我看來,答案是“不”,引用可能未聲明的變量并不是一種好形式-如果由于某種原因在try:
before 中遇到錯誤x = 5
,那么您將得到嘗試時出錯print(f"x = {x}")
。
更重要的是,為什么哦為什么要在 try 塊中分配變量?我想說一個好的經驗法則是只包含在try
您實際測試異常的那部分代碼中。
旁注:
之前我曾被告知使用 a 是不好的形式
except Exception
,因為您真正應該做的是處理某個type
錯誤,或者更好的particular
錯誤(例如except IndexError
,這將導致所有其他類型的錯誤都無法處理) ...try / except
如果非專門使用,很容易引入難以診斷的錯誤。我很確定
except:
并且except Exception
是等效的。

TA貢獻1834條經驗 獲得超8個贊
在這樣的情況下,如果在異常之后有一個共同的執(zhí)行路徑,我通常會做這樣的事情(就if/else變量賦值而言,它有一定的-ish接觸):
try:
price = get_min_price(product)
except Exception as ex:
print("could not get price for product {}: {}".format(product, ex))
price = 1000000.0
print(f"price = {price}")
if price <= min_price:
send_price_alert(user, product, price)
然而,通常情況下,我以這樣一種方式構建我的代碼:無論在try塊中填充什么變量,我都不會在except塊之后使用:
try:
price = get_min_price(product)
print(f"price = {price}")
if price <= min_price:
send_price_alert(user, product, price)
except Exception as ex:
print("could not get price for product {}: {}".format(product, ex))
此處,price不在except關鍵字之后使用,因此無需初始化。
添加回答
舉報