繁体   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