How expensive are exceptions? To find out, perform the following experiment. Consider the following functions square1() and square2(). Both of them return the square of a value, but sqaure1() returns the square normally, while square2() throws it in an exception:
def square1(x):
return x * x
class Answer(Exception):
def __init__(self, x):
self.x = x
def square2(x):
raise Answer(x * x)Write a program that adds the squares of the numbers from 1 to 10,000,000 in two ways, first by calling square1(), then by calling square2() and using a try...except block. Use the time.time() function to measure the total cost of adding these squares in each of these ways.