簡體   English   中英

嘗試/除非未捕獲到“大於”錯誤

[英]Try/Except not catching a “greater than” error

以下代碼不起作用:

try:
    get_current_player(request).cash >= bid # does the player have enough cash for this bid ?
except ValueError:
    messages.error(request, "You don't have the necessary funds to place a bid of <span class='cash'>%d</span> !" % (bid))
messages.success(request, "You placed a bid of %d !" % (bid))

當出價高於當前玩家的現金時,將顯示成功消息,而不是錯誤消息。

但是,以下代碼可以正常工作,表明值正確:

if get_current_player(request).cash >= bid : # does the player have enough cash for this bid ?
    messages.success(request, "You placed a bid of %d !" % (bid))
else :
    messages.error(request, "You don't have the necessary funds to place a bid of <span class='cash'>%d</span> !" % (bid))

我是否使用try / except錯誤?

是的,您使用的是try / except錯誤。 比較不會拋出任何異常,因為如果結果為False,這不是例外。 您的第二個代碼是處理此類問題的正確方法。

您不應該使用try /, except您希望比較get_current_player(request).cash >= bid始終有效並且不會產生錯誤。 在第二段代碼中使用if / else

在您的第一段代碼中,嘗試get_current_player(request).cash >= bid並將其評估為True / False 只要此比較不產生ValueError (並且沒有明顯的原因), except塊就不會執行。

僅僅因為比較評估為Falseexcept塊將不會運行。

編輯 :如果您認為評估get_current_player(request).cash >= bid可能引發異常,則可以將if / else塊放在try塊中:

try:
    if get_current_player(request).cash >= bid:
        messages.success(request, "You placed a bid of %d !" % (bid))
    else:
        messages.error(request, "You don't have the necessary funds to place a bid of <span class='cash'>%d</span> !" % (bid))

except ValueError:
    # handle the ValueError

您可能希望允許比較也可能觸發的任何其他錯誤(例如AttributeError )。

為什么這個

get_current_player(request).cash >= bid

應該返回錯誤? 錯了嗎 不。這就是為什么您對此沒有ValueError的原因。

暫無
暫無

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

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