You have undoubtedly seen exceptions in your programs. When your program didn't
run correctly because of some error, you were experiencing an exception. Some
exceptions you may have seen are
IndentationError. These occur when there is unexpected behavior in the program
and the computer does not know how to recover. You can tell your program how to
handle behavior that may be unexpected though. The best way to do that is to
simply create an if statement that accounts for things like dividing by zero. If
you cannot account for it using an if statement though you can wrap your code
in a special kind of block. This is called a try, except block.
try: unsafeOperation() except Exception as e: print("The universe is now crumbling. If only you had been safe.") print(str(e))
Since this is a block, it looks very similar to the other blocks we have
created. We put a colon at the end of the statement and then make sure that the
body of the block is indented. We can catch the specific type of error we might
be expecting or we can simply catch all errors by only declaring except without
any Error. We can also catch all errors by declaring
except Exception as e if
we want to access the Exception variable.
Try catching a
ZeroDivisionError by dividing by zero!
It is important to try to catch any exceptions that may crop up in your code so that your code will continue to run. Exceptions are the kind of thing that can ruin your day. They are fatal to your program which means that it will stop running. By handling the errors we can ensure that our programs continue to execute even when unexpected things occur.