Error Handling


In an ideal world, users would use our programs as we intend, and enter the values we would expect, and everything would be wonderful. Unfortunately, the reality is quite different. Users enter in all sorts of garbage as input, and so we need to write code defensively, so as to cater for this. One method to do this is using TRY CATCH.

Try Catch

When an error occurs, Python throws an exception. What does that mean? Well, the Python interpreter realises something has gone awry and constructs a special kind of composite data type known as an Object containing information about what went wrong and returns that Object so it can be managed or inspected. This Object is called an Exception.

The terminology we use for the exception being returned by Python is "to throw an exception". Now, if we do not catch this exception that is thrown, our program will exit prematurely and a nasty looking error message will appear on our screens.

As an example:

print "Hello %d" % ("Bob")

If you run this in the Python interactive interpreter, you will see the following error message:

Traceback (most recent call last):
  File "", line 1, in 
TypeError: %d format: a number is required, not str

This is the contents of the Exception, which basically is telling us that it was expecting a number because of the %d, but a string was passed to it. Now, if we were to catch that error in our code, we could handle the situation more gracefully. Let's take a look at what this would look like.

    print "Hello %d" % ("Bob")
    print "Oops, an error has occured."

What is happening here, is we are telling Python to try and run the code inside the try block, and if anything goes wrong, execute the code in the except block.

This is very useful, especially when dealing with user input.


Rewrite the following statements by enclosing them in TRY CATCH statements.

  1. answer = 5.00 * "Bubblegum"
  2. num = null / 0
  3. some_value = 1239 / 0

Continue to next section


comments powered by Disqus