Sometimes we want to design our code so we read a set of numbers from
a file or from standard input without knowing in advance how many
there are. When we run out of input (reach the end of file), we
stop. Here is the naive way to do it. In this example we are reading
from standard input, but we could just as well be reading a file one
line at a time.
Trueis always true, so the while loop might run forever, but when you reach the end of the input, Python quits with an error message. This is ugly. What we would like to do is to catch this error condition and exit gracefully. Here is how
try:statement tells Python that you are going to attempt something that might create an error condition. The statement(s) in the block below it will always be executed. The
exceptstatement allows for error handling. That statement works a bit like an
ifstatement. If the
exceptstatement includes one of the Python error types, the statement(s) in the indented block below it will be executed. Here we break out of the
whileloop. Otherwise, control is passed to the statement after that block, which, in this case, will “do stuff” using the value that was read. If the
exceptstatement does not specify any error type, any error will cause it to execute the indented block. To find out what the error condition is called, run your code without catching the error, and Python will give it to you along with the error message when your code crashes.