Exceptions
Even though we have not covered the topic yet, we expect that by now you have at least a vague idea of what an exception is. In the previous chapters, we saw that when an iterator is exhausted, calling next()
on it raises a StopIteration
exception. We got an IndexError
when we tried accessing a list at a position that was outside the valid range. We also encountered AttributeError
when we tried accessing an attribute that did not exist on an object, and KeyError
when we tried to access a nonexistent key in a dictionary. In this chapter, we will discuss exceptions in more depth.
Even though an operation or a piece of code is correct, there are often conditions in which something may go wrong. For example, if we are converting user input from str
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 might attempt a division by zero. When...