try and except: a program that does not crash
The try and except blocks make a program calm when a mistake happens. Python first tries the lines under try. If everything works, the except block is skipped. If a ValueError happens, Python jumps straight to except ValueError and runs its lines. The message should tell the user what to do, such as Please type digits only, not just Error. There is a shorter form, a bare except with no error name. It catches every kind of error, even our own typing mistakes inside the try block, and then shows a message that is wrong. So the better habit is to name the error you expect. Note the layout: try: and except ValueError: are on their own lines, with the code under them indented.
1try: 2 books = int(input("How many books? ")) 3 print("Next year:", books + 1) 4except ValueError: 5 print("Please type digits only.")
How many books? seven Please type digits only.
| Typed | Screen shows |
|---|---|
| "7" | Next year: 8 |
| "seven" | Please type digits only. |
| "" (nothing) | Please type digits only. |
| "5.5" | Please type digits only. |
1try: 2 books = int(input("How many books? ")) 3 print("Next year:", bookz + 1) 4except: 5 print("Please type digits only.")
How many books? 7 Please type digits only.
On paper, write a try and except ValueError program that asks how many pencils there are and shows the number plus 10. Write a good message for the except block. Then say what the screen shows for the typed values 3 and three.