[Tutor] Input to python executable code and design question

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jan 10 19:47:06 CET 2005



> >To help you out. You need some sort of error checking to be sure that
> >within your given range you won't get something like a math domain
> >error.
> >
> >
> Yes, I thought that:
> try:
>     #function
> exception:
>     pass


Hi Ismael,


Python's keyword for exception handling is 'except', so this can be
something like:

###
try:
    some_function()
except:
    pass
###


... Except that the 'except' block should seldom be so vacant like that.
*grin* There are two things we should try to do when exception handling:
handle only what we need, and report exception information when we do.


We really want to get the system to handle only domain errors, and
otherwise let the exception raise errors.  But because the block above
catches every Python error, even silly things like misspellings, it will
sweep programmer errors under the carpet.


For example, the code snippet:

###
>>> def sqrt(x):
...     return y**0.5      ## bug: typo, meant to type 'x'
...
>>> try:
...     sqrt("hello")
... except:
...     pass
...
###

tries to make it look like we're catching domain errors, but the
overzealous exception catching disguises a really silly bug.


We can make the exception more stringent, so that we only catch domain
errors.  According to:

    http://www.python.org/doc/lib/module-exceptions.html

there's are a few standard exceptions that deal with domains, like
ArithmeticError, ValueError, or TypeError.


Let's adjust the code block above so we capture only those three:

###
>>> try:
...     sqrt("hello")
... except (ArithmeticError, ValueError, TypeError):
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
  File "<stdin>", line 2, in sqrt
NameError: global name 'y' is not defined
###



Also, it might be a good idea to print out that a certain exception
happened, just so that you can tell the user exactly what's causing the
domain error.  The 'traceback' module can help with this:

    http://www.python.org/doc/lib/module-traceback.html


For example:

###
try:
    1 / 0
except:
    print "There's an error!"
###

tells us that some wacky thing happened, but:


###
import traceback
try:
    1 / 0
except:
    print "Error:", traceback.format_exc()
###

tells us that the error was caused by a ZeroDivisionError.



Best of wishes to you!



More information about the Tutor mailing list