Exceptions
Even though we haven't formally introduced them to you, by now we expect you to at least have a vague idea of what an exception is. In the previous chapters, we've seen that when an iterator is exhausted, calling next
on it raises a StopIteration
exception. We met IndexError
when we tried accessing a list at a position that was outside the valid range. We also met AttributeError
when we tried accessing an attribute on an object that didn't have it, and KeyError
when we did the same with a key and a dictionary.
Now the time has come for us to talk about exceptions.
Sometimes, even though an operation or a piece of code is correct, there are conditions in which something may go wrong. For example, if we're converting user input from string
to int
, the user could accidentally type a letter in place of a digit, making it impossible for us to convert that value into a number. When dividing numbers, we may not know in advance whether we're...