June 2017
Beginner
352 pages
8h 39m
English
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 try … except ZeroDivisionError construct and then raise a new ValueError exception from inside the exception handler.
def sqrt(x): ...
Read now
Unlock full access