Exceptions are an important aspect of the API of a function. Callers of a function need to know which exceptions to expect under various conditions so that they can ensure appropriate exception handlers are in place. We'll use square-root finding as an example, using a home-grown square-root function, courtesy of Heron of Alexandria (although he probably didn't use Python).
Callers of a function need to know which exceptions to expect:
Figure 6.1: Callers need to know now
Place the following code in a file roots.py:
def sqrt(x):
"""Compute square roots using the method of Heron of Alexandria.
Args:
x: The number for which the square root is to be computed.
Returns:
The square root of x.
"""
guess = x
i = 0
while guess * guess != x and i < 20:
...