加载中...

Python

  1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Exceptions, Errors, and Warnings

From Al Lukaszewski, for About.com

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

More from About.com

Build Your Own Website

Easy guides to creating your own blog, online photo album or wiki.

Connect Your Home Computers

Easy ways to connect two computers for networking purposes.

Python

  1. Home
  2. Computing & Technology
  3. Python

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

All rights reserved.