Catching exceptions

Let's modify our code to catch the exception before it propagates up to the top of the call stack (thereby causing our program to stop) using the tryexcept construct:

def main():
print(sqrt(9))
print(sqrt(2))
try:
print(sqrt(-1))
except ZeroDivisionError:
print("Cannot compute square root of a negative number.")

print("Program execution continues normally here.")

Now when we run the script we see that we're handling the exception cleanly:

$ python sqrt.py
3.0
1.41421356237
Cannot compute square root of a negative number.
Program execution continues normally here.

We should be careful to avoid a beginners mistake of having too-tight scopes for exception handling blocks; we can easily use one tryexcept block for all of our calls to sqrt(). We also add a third print statement to show how execution of the enclosed block is terminated:

def main():
try:
print(sqrt(9))
print(sqrt(2))
print(sqrt(-1))
print("This is never printed.")
except ZeroDivisionError:
print("Cannot compute square root of a negative number.")

print("Program execution continues normally here.")
..................Content has been hidden....................

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