Catching an Error
Some exceptions you can prevent with an if, like the empty list in the previous exercise. Others are hard to see coming. In a form on a website, people can type anything into the field for the number of tickets. The program converts the text with int(), and when someone types two, it ends:
tickets_text = "two"
tickets = int(tickets_text)Traceback (most recent call last):
File "<exec>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'two'It's a ValueError: int() got text, which is the right type, but not a whole number written in digits. (Base 10 means the ten digits we usually count with.)
You can't check every possible text with if. Instead, you let Python try, and say what to do if it fails. That's what try and except are for:
tickets_text = "two"
try:
tickets = int(tickets_text)
print("Tickets:", tickets)
except ValueError:
print("Please enter a number.")
print("Thank you!")Please enter a number.
Thank you!How it works:
- Python runs the block under
try:line by line. - When a line raises a
ValueError, Python leaves thetryblock right there: the rest of it doesn't run. It runs the block underexcept ValueError:instead. The program catches the exception. - After the
exceptblock, the program goes on with the next line. It doesn't end. - When nothing goes wrong, Python skips the
exceptblock. Withtickets_text = "2", the program printsTickets: 2andThank you!
Put the line that can fail into the try block, together with the lines that need its result. When int() fails, tickets gets no value, so a print(tickets) below the except block would end with a NameError.
As with if and else, try: and except ValueError: end with a colon, and their blocks are indented. A try without an except doesn't run at all: SyntaxError: expected 'except' or 'finally' block. (You'll meet finally later in this lesson.)
Instructions
- 1
The program ends with a
ValueError. Put the line withint()and theprint()of the price into atryblock, and addexcept ValueError:with a block that printsPlease enter a number.The program then printsPlease enter a number.andThank you for your order.Try it: change"two"to"3"(To pay: $24), and then back. The exercise also tries other texts. - 2
At the end of the program, add up the tickets in
orders, the texts that people typed during the day. Go through them with aforloop, and put the conversion and the adding into atryblock. For a text that isn't a number, printSkipped: three(with the text), and the loop goes on with the next order. After the loop, printTickets sold: 7.