June 2017
Beginner
352 pages
8h 39m
English
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 try … except 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.py3.01.41421356237Cannot 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 try … except block for all of ...
Read now
Unlock full access