Raising exceptions explicitly

This is an improvement on what we started with, but most likely users of a sqrt() function don't expect it to throw a ZeroDivisionError.

Python provides us with several standard exception types to signal common errors. If a function parameter is supplied with an illegal value, it is customary to raise a ValueError. We can do this by using the raise keyword with a newly created exception object which we can create by calling the ValueError constructor.

There are two ways in which we could deal with the division by zero. The first approach would be to wrap the root-finding while-loop in a tryexcept ZeroDivisionError construct and then raise a new ValueError exception from inside the exception handler.

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
try:
while guess * guess != x and i < 20:
guess = (guess + x / guess) / 2.0
i += 1
except ZeroDivisionError:
raise ValueError()
return guess

While it works, this would be wasteful; we would knowingly proceed with a non-trivial computation which will ultimately be pointless.

Figure 6.2: Wasteful
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset