【问题标题】:Exception doesnt display the message that a previously raised exception has异常不显示先前引发的异常具有的消息
【发布时间】:2018-08-18 18:59:30
【问题描述】:

所以我试图使用Exception as e:,但变量 e 不会显示我之前分配给它的消息。你能帮帮我吗?

SERVICE_CHARGE= 2
TICKET_PRICE = 10
tickets_remaining= 100

def calculate_price(number_of_tickets):
    return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE

while tickets_remaining:
    print "There are {} tickets remaining".format(tickets_remaining)

users_name=raw_input("What's your name?  ")

try:
    number_of_tickets=int(input("{}, how many tickets would you like to buy?  ".format(users_name)))
    if number_of_tickets>tickets_remaining:
        raise Exception("Not enough tickets remaining")       
except Exception as err:
    print "Im sorry. {}. Please try again!".format(err)

【问题讨论】:

  • 不确定为什么有些代码被排除在代码块之外。我也想知道!

标签: python exception raise


【解决方案1】:

这是因为当你把Exception写成e时,e就变成了Exception中存储的值的别名,即e临时存储了Exception的值,然后将其丢弃(变为未定义)。您应该使用(您在问题中提到变量 e 但在代码中使用 err):

except Exception:
    print "Im sorry. {}. Please try again!".format(err)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    相关资源
    最近更新 更多