Which Error?
except ValueError: catches only a ValueError. Any other exception in the try block still ends the program, with its traceback. That's how it should be: an except is for a problem you expect, such as text that isn't a number, while a mistake you didn't expect should show up, so that you can fix it.
When a try block can fail in more than one way, give it an except for each type of exception:
prizes = {1: "a gold medal", 2: "a silver medal", 3: "a bronze medal"}
place_text = "5"
try:
place = int(place_text)
print("You get", prizes[place])
except ValueError:
print("The place must be a number.")
except KeyError:
print("Only the first three places get a prize.")
print("Thanks for taking part!")Only the first three places get a prize.
Thanks for taking part!The keys of prizes are numbers, which works too. prizes[5] raises a KeyError, so Python looks at the except blocks from the top and runs the first one whose type matches. As with elif, only one of them runs. With place_text = "second", int() raises a ValueError, and the program prints The place must be a number. When two types should be handled the same way, one except can name both, as a tuple: except (ValueError, KeyError):.
You can also write except: without a type. It catches every exception, and that's the trouble: it catches your own mistakes too. Can you spot the one here?
age_text = "14"
try:
age = int(age_text)
print("Next year you'll be " + age + 1)
except:
print("The age must be a number.")The age must be a number.The age is "14", a perfectly good number, but the program says it isn't. What really went wrong is a TypeError in the print(): text and a number can't be joined with +. The except: caught it and hid it behind the wrong message. With except ValueError:, the program would end with TypeError: can only concatenate str (not "int") to str and the number of the line, and you'd fix it in a few seconds. So always name the exception you expect.
A SyntaxError in your program can't be caught: with one, nothing runs, not even the try.
Instructions
- 1
The program says the count isn't a number, although
count_textis"2". Replaceexcept:withexcept ValueError:and run the program again: now you see what really went wrong. Fix it. The program then prints2 x tea: $4. - 2
Change
itemto"juice"and run the program: it ends with aKeyError, because the coffee shop doesn't sell juice. Add a secondexceptblock, forKeyError, that printsSorry, we don't have juice.with the name of the item fromitem. Then changeitemback to"tea": the exercise also tries your program with other items and counts.