Catching any exception an printing it

Fredrik Lundh effbot at telia.com
Mon Feb 21 15:13:37 EST 2000


Stuart Reynolds <S.I.Reynolds at cs.bham.ac.uk> wrote:
> Python allows you to do,
>
> try:
>   if a:
>      raise SomeException()
>   else:
>      raise xyz()
> except:
>   print 'There was an error'
>
> but is it possible to print out the exception if you don't know what
> type it is? I'd like the above error message to be more useful, but the
> exception raised inside the try block could be anything. Is it possible
> to find the last exception raised?

inside the except clause, sys.exc_info() returns information
about the current exception.  for details, see:
http://www.python.org/doc/current/lib/module-sys.html

to print the full exception traceback (like the interpreter does
if you don't catch the exception at all), use the traceback
module:

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

hope this helps!

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list