Search code examples
pythonexceptionstring-formatting

Formatting exceptions as Python does


If I raise an Exception in Python, here's what I get:

raise Exception("Hello world")
Traceback (most recent call last):

  File "<ipython-input-24-dd3f3f45afbe>", line 1, in <module>
    raise Exception("Hello world")

Exception: Hello world

Note the last line that says Exception: Hello world. Given an Exception (foo = Exception("Hello world")), how can I produce text like this? None of the following work:

str(foo)
Out[27]: 'Hello world'

repr(foo)
Out[28]: "Exception('Hello world',)"

"{}".format(foo)
Out[29]: 'Hello world'

"{}: {}".format(type(foo), foo)
Out[30]: "<type 'exceptions.Exception'>: Hello world"

Solution

  • If your exception object is exc, then:

    • The part before the colon is type(exc).__name__.
    • The part after the colon is str(exc).

    So you can just do this:

    print('{}: {}'.format(type(exc).__name__, exc))