Logo         Community
The Company
Your Account
Contact Us
Python 101 (part 8): An Exceptionally Clever Snake
Use Python's exception handlers to avoid violent - and potentially embarrassing - flame-outs.

| Anatomy Of An Exception |

No developer, no matter how good (s)he is, writes bug-free code all the time. Which is why most programming languages - including Python - come with built-in capabilities to catch errors and take remedial action. This action could be something as simple as displaying an error message, or as complex as heating your computer's innards until they burst into flame (just kidding!)

Normally, when a Python program encounters an error, be it syntactical or logical, it exits the program at that stage itself with a message indicating the cause of the error. Now, while this behaviour is acceptable during the development phase, it cannot continue once a Python program has been released to actual users. In these "live" situations, it is unprofessional to display cryptic error messages (which are usually incomprehensible to non-technical users); rather, it is more professional to intercept these errors and either resolve them (if resolution is possible), or notify the user with a clear error message (if not).

The term "exceptions" refers to those errors which can be tracked and controlled. For example, if a function attempts an unsupported operation on a built-in Python object (say, modifying an immutable object), Python will generate a "TypeError" exception, together with a stack trace or detailed explanation of the problem. Exceptions like these can be caught by the application, and appropriately diverted to an exception-handling routine.

An example might make this clearer. Consider the following Python program,


# set up tuple
dessert = ('apple pie', 'chocolate fudge cake', 'icecream')

# change tuple value
dessert[1] = 'chocolate brownies'

which generates a TypeError because I'm trying to modify a tuple.

''.preg_replace(array('/  /', '/ /'), array('  ', '   '), '
Traceback (innermost last):
  File "dessert.py", line 5, in ?
    dessert[1] = 'chocolate brownies'
TypeError: object doesn't support item assignment

Now, let's add some code to trap and handle the exception gracefully.


# try running this code
dessert = ('apple pie', 'chocolate fudge cake', 'icecream')
dessert[1] = 'chocolate brownies'
except TypeError:
# if error, do this...
print "Whoops! Something bad just happened. Terminating script."

And this time, when the script is executed, it will not generate a TypeError - instead, it will output

''.preg_replace(array('/  /', '/ /'), array('  ', '   '), '
Whoops! Something bad just happened. Terminating script.

This is a very basic example of how Python exceptions can be trapped, and appropriate action triggered. As you will see, the ability to handle errors in a transparent manner throws open some pretty powerful possibilities...

How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.

Read more, or grab your copy now!

previous page more like this  print this article  next page
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
In cut!...
American Chai
The Core
Find out how you can use this article on your own Web site!

Copyright © 1998-2018 Melonfire. All rights reserved
Terms and Conditions | Feedback