1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Exceptions, Errors, and Warnings

From , former About.com Guide

5 of 8

Taking Exception

While it is all well and good to handle an exception and do something predictable when it happens, what if you want to process the error as data, perhaps printing it in a bold HTML typeface? Simply pass to except the variable by which you want to reference the error data. Using the last example from the previous page, it would look like this:

a = input("Please enter the dividend (the number to be divided):")
b = input("Please enter the divisor (the number by which to divide):")

try:
    print a/b
except (NameError, ZeroDivisionError), error:
    print "The divisor must not be zero. When the divisor is zero, Python hiccups like every good calculator should. The error passed was:"
    print "<div><b>%s</b><div>" %(error)

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.