Week 3
Exceptions
Bad input does not have to crash the program. You can notice it and ask again.
Some mistakes happen while Python is reading your file. That is a SyntaxError, and the program never starts. Other mistakes happen while it is running: a ValueError when text cannot become a number, a NameError when you use a name you never defined, a ZeroDivisionError when you divide by zero.
Try wraps the lines that might fail. Except names the error you are ready for and says what to do instead. Else on a try runs only when nothing failed. Raise is how you announce an error yourself. Pass means 'do nothing', which is rarely what you want, but it is how you write a placeholder.
A fresh example: ask for a whole number, and if the person types a word, say so and ask again. You are catching one kind of error on purpose. You are not catching every possible error, or you will hide bugs.
Problems
- Fuel GaugeTurn a fraction into a percent, and ask again when the fraction is not usable.
- Felipe's TaqueriaLook each item up, add its price, and ignore anything that is not on the menu. Stop when the person ends input.
- Grocery ListCount repeated items, then show them in order.
- OutdatedTurn a month name into a month number, and ask again when the date is not real.