Python Exception Handling

(1/1)

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:
Code:

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


Now, obviously unless there is a file called missing modulename.py 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
Code:

Exception(*)
       |
       +-- 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)

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

Navigation

[0] Message Index