Python Python Basics All Together Now Handle Exceptions

How does the ValueError as err work?

How does the code know to use the ValueError raised in the try block when the ValueError was never assigned to err? For Example:

 try:
     ticket_count = int(ticket_count)
     # Raise a ValueError if the request is for more tickets than are avaliable
     if ticket_count > tickets_remaining:
         raise ValueError("There are only {} tickets remaining".format(tickets_remaining))
except ValueError as err:
     # Include the error text in the output
     print("Oh no! We ran into an issue. {}. Please try again".format(err))

1 Answer

Steven Parker
Steven Parker
171,252 Points

It's the "except" statement that makes the assignment to "err". It looks strange because normally a variable being created and assigned goes on the left followed by an equal sign, and here it's on the right and after the word "as".

But that's what "as err" is doing — assigning the variable "err" with the message that comes along with the exception.

Thank you, that makes more sense now!