proper way to get nice string from exception

715 views Asked by At

I want to generate a one-line string from an Exception which tells me what happened where (don't need a full backtrace). The following information would be nice:

  • filename / linenumber
  • exception type
  • exception description (what you get from str(e))
  • nice to have: function/method/class

Currently I do the following:

import os
...
try:
    os.nonexisting()
except Exception as e:
    t = e.__traceback__
    tbf = e.__traceback__.tb_frame
    print('%s:%d: %s in %s(): "%s" ' %
        os.path.basename(tbf.f_code.co_filename),
        t.tb_lineno,
        e.__class__.__name__,
        tbf.f_code.co_name, e))

which gives me:

foo.py:203: AttributeError in foo(): "'module' object has no attribute 'nonexisting'"

Is there a more elegant way to print out the details given in this example? I'm thinking about s.th. like

print(e.format('%f: %l: %t %F: "%w"'))

I'd like to avoid importing extra modules except there is one exactly for this purpose.

1

There are 1 answers

2
Daniel Roseman On

I think traceback.format_exception_only does exactly what you want.

try:
    os.nonexisting()
except Exception as e:
    print(traceback.format_exception_only(e.__class__, e))