[Tutor] Trapping Interpreter errors as a string
Remco Gerlich
scarblac@pino.selwerd.nl
Tue, 27 Feb 2001 08:10:09 +0100
On Mon, Feb 26, 2001 at 06:33:36PM -0900, Tim Johnson wrote:
> Am looking for a way to trap python errors as a string.
> A quick example would be like the disarm function in the rebol language.
>
> To be more specific:
> Let's say I had a simple cgi program to first sent the the mime-type
> print "Content-type: text/html\n"
>
> then I do something dumb, like
>
> 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 = ?
>
> Then the programmer could gracefully complete the output form with
> the error message within it.
In Python, you would usually make something like this:
try:
x = string.atoi("duh")
except ValueError, problem:
print problem
This will print "invalid literal for int(): duh" and then continue. You put
whatever code you need to handle the exception in the except: block. You can
look at sys.exc_info for more information on the current exception, or
inspect the traceback and/or print it with functions from the traceback
module.
If you don't know about exceptions yet, read chapter 8 of the Tutorial.
--
Remco Gerlich