简体   繁体   中英

Try/Except not catching a “greater than” error

The following code does not work :

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))

When the bid is higher than the current player's cash, the success message is printed instead of the error message.

However, the following code works, indicating the values are correct :

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))

Am I using try/except wrong ?

Yes, you are using try/except wrong. Comparison does not throw any exceptions, because it is not exceptional if the outcome is False. Your second code is the correct way to handle such a problem.

You shouldn't use try / except if you expect the comparison get_current_player(request).cash >= bid to always work and not produce an error. Use if / else as in your second block of code.

With your first block of code, get_current_player(request).cash >= bid is tried and evaluated to True / False . As long as this comparison doesn't produce a ValueError (and there's no obvious reason why it should), the except block doesn't execute.

The except block will not run just because the comparison evaluated as False .

Edit : If you think there is a possibility that evaluating get_current_player(request).cash >= bid will raise an exception, you could put the if / else block inside the try block:

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

You may want to allow for any other errors the comparison could trigger too (eg AttributeError ).

Why this

get_current_player(request).cash >= bid

should return Error? Is this wrong? No. Thats why u dont have ValueError on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM