Originally Published: Wednesday, 30 August 2000 Author: Jason Tackaberry
Published to: develop_articles_tutorials/Development Tutorials Page: 5/6 - [Printable]

Programming with Python - Part 1: Baby Steps

This tutorial is the first in a series that will introduce you to Python, a dynamic, object-oriented language that is rapidly gaining popularity. Since I myself have garnered a modest Perl background before learning Python, I will target this tutorial at the Perl programmer. However, anyone with a little programming experience should find this text useful.

  << Page 5 of 6  >>

An Exception to the Rule

Error handling in Python is done using exceptions. When a statement or expression is executed, it may need to signal some sort of error message. It does this by raising an exception. For example, suppose we try to open a file that doesn't exist:

  file = open("/etc/password")

Executing this code will output:

  Traceback (innermost last):
    File "example.py", line 1, in ?
      file = open("/etc/password")
  IOError: [Errno 2] No such file or directory: '/etc/password'

Obviously it's not acceptable to have your program bail out every time it encounters an error as simple as a non-existent file. In Python, you first try the code, and can specify a block of code to be executed upon one, many, or all exceptions:

  try:
    file = open("/etc/password")
  except:
    print "Open failed!"

Now, if the open fails, it will print "Open failed!" and move on. It's entirely possible (and likely) that an expression can generate more than one exception. So in our example, we may just want to handle IOError exceptions. We can do this by specifying the exception type after the except keyword:

  try:
    file = open("/etc/password")
  except IOError:
    print "Open failed!"

But there are different kinds of IOErrors; the file may not exist, or perhaps it is not readable to the user trying to open it. Note in the exception error generated above, the No such file or directory error number was 2. Exceptions may have arguments associated with them, and we can fetch these arguments like so:

  try:
    file = open("/etc/password")
  except IOError, (errno, message):
    if errno == 2:
      print "File does not exist, cannot open"
    else:
      print "Unhandled error", errno, message

The IOError is one of many built-in exceptions. You can create your own custom exceptions, as well. In fact, the exception may be identified by either strings or instance objects. (You can identify an exception by a class object, but Python will just use that class object to create an instance before raising the exception.) A simple example of raising an exception identified by a string is:

  def bailout():
    raise "MyError", (1, 2, "x y z")

  try:
    bailout()
  except "MyError", info:
    print "Handled MyError exception with", info





  << Page 5 of 6  >>