1. Home
  2. Computing & Technology
  3. Python

Part 4: Handling Errors the Way You Want

By Al Lukaszewski, About.com

6 of 7

How to Handle the Error / Exception in Python

Errors or exceptions come in all shapes and sizes. A full list of Python's errors and warnings can be found under the Python Modules category. In our RSS Reader, we will use a fairly general approach to error handling with the block statement try...except. For more nuanced error handling methods, you will want to see my tutorial on the subject.

We add try...except in the main() function like this:

def main():
     try:
          output = formBody(feedname)
          print output

     except:
          print "There is an error with that feed. If the problem persists, please contact the site administrator. For now, please choose another feed."

Now, whenever an error occurs in the program's processing of a feed, the user will receive a message informing them of the problem. If we used multiple except statements, we would be able to customise the error message for each problem that might arise. All exceptions are now handled explicitly, even though the exact error is not stated. The exact error can be determined behind-the-scene. As a matter of good practice, it is not always good security to render public the kind of error that is being thrown; crackers could use that information to the detriment of your website.

6 of 7

Explore Python

More from About.com

  1. Home
  2. Computing & Technology
  3. Python

©2008 About.com, a part of The New York Times Company.

All rights reserved.