1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Exceptions, Errors, and Warnings

From Al Lukaszewski, for About.com

7 of 8

Raising Your Own Exceptions With raise - Part 1

The standard way by which Python "handles" exceptions is by throwing an error of some sort. If the program is not coded to "catch" the error and do something with it, the program usually crashes, as we saw earlier. However, even if the program works just as you intended, you can program in your own exceptions using the raise statement.

At a Python shell, type the following:

raise NameError
You will get feedback from the Python interpreter that looks like this:
>>> raise NameError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError

You can use any kind of error that is included in the module exceptions (for a full list of exceptions, see the page of exceptions). You can also raise your own exceptions (see below). However, the exception raised must be a class or an instance of a class. Anything else will result in a TypeError. If you want to see what would happen, type the following at a Python shell prompt:

>>> raise

Whenever an exception is raised in the code, Python will raise that error -- even if it sees nothing wrong. In this way, your programs can be stricter than the Python interpreter. Say, for example, you have a set of options and would like a NameError error to be thrown if the user chooses an option not listed. Python will do that as part of the exception handling process, instead of throwing a KeyError or something similar.

Explore Python
About.com Special Features

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

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python

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

All rights reserved.