[Tutor] Trapping Interpreter errors as a string

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 28 Feb 2001 03:22:18 -0800 (PST)

On Mon, 26 Feb 2001, Tim Johnson wrote:

> integer = string.atoi("duh")
> Guido will then say:
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for atoi(): duh
> To reduce this inquiry:
> 1)Can that error message be returned to the user as a string.
> 2)Is there a specific numeric error code attached to the error message.
>    i.e. ValueError = ?

It sounds like you might want to use exception handling: Exception
handling often takes the place of error codes in Python programming.

We can get at the ValueError as a string:

>>> try:
...     integer = string.atoi("duh")
... except ValueError, e:
...     print "Something went wrong."
...     print "Error message: ", e
Something went wrong.
Error message:  invalid literal for int(): duh

The idea is that we wrap a try/except block around whatever code might
need some error trapping, and handle exceptional situations appropriately.  
Exception handling should be flexible enough to let you clean up the
situation if its possible, and exit gracefully otherwise.  The Python
tutorial talks about this here:


Hope this helps!