1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Exceptions, Errors, and Warnings

From , former About.com Guide

2 of 8

Exception Exemplified

If reading the previous page has caused you to wonder: "Gee, what does Python do with unexpected variations in data?", try this in your Python shell:

Python 2.5 (r25:51908, Dec 8 2006, 15:53:50)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print a
You will immediately receive Python's response: a NameError.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

If you would like another example, try this one from "Beginning Python":

>>> 1/0

If you have come far enough in life to be reading this, there is a good chance that you know that division by zero is a no-no in the world of non-imaginary numbers. Python may not have been around as long as you have, but it knows that, too, and it has a special error just for it:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

You will notice that this error is called a ZeroDivisionError. Python has many kinds of exceptions. Descriptions of each can be found on the last page of this tutorial. Alternatively, if you just want to get a feel for what kinds of exceptions can be thrown, type the following in your Python shell:

>>> import exceptions
>>> dir(exceptions)

Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python

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

All rights reserved.