Python Exception Handling


Richard Marks:
Okay, a quick blurb about handling errors in your Python code.

Anyone who has been studying Python with me knows that I use try/excepts when importing modules. Like this:

import missingmodulename
except ImportError, errmsg:
print "Could not import module: %s" % (errmsg)
raise SystemExit, errmsg

Now, obviously unless there is a file called missing then the import will fail. What my error checking doe is spits out a nice message informing the user that module missingmodulename could not be imported.
Then my code raises an Exception Error, named SystemExit.
There are several Exception Errors that you can raise as you will see below.

The Standard Exception Hierarchy

       +-- StandardError(*)
            +-- SystemExit
            +-- KeyboardInterrupt
            +-- ImportError
            +-- IOError
            +-- EOFError
            +-- RuntimeError
            +-- NameError
            +-- AttributeError
            +-- SyntaxError
            +-- TypeError
            +-- AssertionError
            +-- LookupError(*)
            |    |
            |    +-- IndexError
            |    +-- KeyError
            +-- NumberError(*)
            |    |
            |    +-- OverflowError
            |    +-- ZeroDivisionError
            |    +-- FloatingPointError
            +-- ValueError
            +-- SystemError
            +-- MemoryError

You can also create your own Exception Errors to raise in your programs.
I suggest reading more on this topic here:
User Defined Exceptions in Python (Guido van Rossum)

I know you use them and I now know to use them in my code as well. It is very helpful.


[0] Message Index