Python Python Basics All Together Now Handle Exceptions

Sai C
Sai C
2,202 Points

raise and ValueError

code

  try:
    numberoftickets = int(numberoftickets)
    if numberoftickets > tickets_remaining:
      raise ValueError("There are only {} remaining".format(tickets_remaining))
  except ValueError as err:

I want to know how exactly does the raise thing work: here we already have if condition: raise ValueError, I think that means if number of tickets is more than tickets remaining, we have a value error and return "there are only xxx tickets remaining" then why do we still need "except ValueError as err"?

Could you post your could so others can see how you wrote it. If you don't know how check the Markdown Cheatsheet

Mark Kastelic
Mark Kastelic
7,400 Points

Hi Sai,

I posted an answer to a very similar question (Difficulty understanding "ValueError as err") back on Nov. 15. 2018, so this may be helpful:

Initially, the split_check function is not called within the try block. As a result, the ValueError is handled exclusively by the function with the raise statement. When Craig moves the split_check function call into the try block, the ValueError is now handled by the except statement in the try block. The message is lost because the try block caught the ValueError raised by the function, and only needs to handle it by executing the single print statement in the except block. In order to "preserve" the string attached to the raise ValueError within the function, it has to be saved as a variable (commonly as "err"). Now, when Craig adds a second print statement to the except block, the contents of err are printed out as well.

1 Answer

Maya Husic
Maya Husic
13,488 Points

Hi Sai,

The except ValueError applies to the answers that are not numbers (example in video used is if user replies 'blue' to 'How many tickets would you like to buy?') as well as if the number of requested tickets exceeds the number of tickets that are actually available, in which case both ValueErrors are invoked with exceeded number one being more specific with text to be printed as err.

Hope this helps. Happy coding.

Maya

Sai C
Sai C
2,202 Points

do you mean with

      raise ValueError("There are only {} remaining".format(tickets_remaining))

we are dealing with 1st kind of ValueError problem, say input = 101 while remaining =100

and with

  except ValueError as err:
    print("not valid value")

we deal with 2nd kind of ValueError or when users reply "blue"? Then why do we have to store the 2nd Value Error into err, we could've just used "except ValueError"?