异常不显示先前引发的异常具有的消息

时间:2018-08-18 18:59:30

标签: python exception raise

因此,我尝试使用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)

1 个答案:

答案 0 :(得分:0)

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

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