2 回答

TA贡献2036条经验 获得超8个赞
在极少数情况下, 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个赞
在这样的情况下,如果在异常之后有一个共同的执行路径,我通常会做这样的事情(就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关键字之后使用,因此无需初始化。
添加回答
举报