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.

The idea
If the input is bad, ask again Ask Bad input: ask again again

Problems