Displaying error message in a try except?

Fredrik Lundh fredrik at pythonware.com
Sun Dec 11 17:30:47 EST 2005


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

for more info, see the library reference.

hope this helps!

</F>






More information about the Python-list mailing list