1

以下代码不起作用:

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 错误吗?

4

3 回答 3

3

是的,您使用的是 try/except 错误。比较不会引发任何异常,因为如果结果为 False,则不会出现异常。您的第二个代码是处理此类问题的正确方法。

于 2014-10-05T16:21:44.250 回答
0

如果您希望比较始终有效并且不会产生错误,则不应使用try/ 。在您的第二个代码块中使用/ 。exceptget_current_player(request).cash >= bidifelse

使用您的第一个代码块,get_current_player(request).cash >= bid尝试并评估为True/ False。只要这种比较不产生 a ValueError(并且没有明显的理由为什么它应该产生),该except块就不会执行。

except块不会仅仅因为比较评估为False.

编辑:如果您认为评估有可能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)。

于 2014-10-05T16:21:53.017 回答
0

为什么这个

get_current_player(request).cash >= bid

应该返回错误?这是错的吗?不,这就是为什么你没有 ValueError 。

于 2014-10-05T16:22:26.260 回答