Displaying error message in a try except?
Tim Williams (gmail)
tdwdotnet at gmail.com
Sun Dec 11 18:28:31 EST 2005
On 11/12/05, Fredrik Lundh <fredrik at pythonware.com> wrote:
>
> wawork at hotmail.com wrote:
>
> > Fairly new to python. In a try except how do you display the true
> > (raw) error message so it can be displayed back to the user?
>
> assuming that "true" means "the message you would get if you hadn't
> used a try/except", the traceback module is what you want:
>
> import traceback
>
> try:
> raise SyntaxError("example")
> except:
> traceback.print_exc()
>
> prints
>
> Traceback (innermost last):
> File "module.py", line 4, in ?
> SyntaxError: example
>
> more here:
>
> http://effbot.org/librarybook/traceback.htm
>
> you can also inspect the exception status via the sys.exc_info() call.
> e.g.
>
> import sys
>
> try:
> 1/0
> except:
> print "%s: %s" % sys.exc_info()[:2]
>
> prints
>
> exceptions.ZeroDivisionError: integer division or modulo by zero
>
>
Or you can combine both, I find these 3 lines after the except most helpful
during developement stages and liberally splatter them around prototype code
>>> import sys, traceback
>>> try:
... 1/0
... except:
... print sys.exc_info()[0]
... print sys.exc_info()[1]
... print "LINE=",traceback.tb_lineno(sys.exc_info()[2])
...
exceptions.ZeroDivisionError
integer division or modulo by zero
LINE= 2
>>>
HTH :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20051211/ef3bd61d/attachment.html>
More information about the Python-list
mailing list