Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 424
kuzzooroo Avatar asked Feb 19 '16 06:02

kuzzooroo


People also ask

What is a format exception?

A FormatException exception can be thrown for one of the following reasons: In a call to a method that converts a string to some other data type, the string doesn't conform to the required pattern. This typically occurs when calling some methods of the Convert class and the Parse and ParseExact methods of some types.

What does exception as Python mean?

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

What are the 3 major exception types in Python?

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

Does raising an exception stop execution Python?

When an exception is raised, no further statements in the current block of code are executed. Unless the exception is handled (described below), the interpreter will return directly to the interactive read-eval-print loop, or terminate entirely if Python was started with a file argument.


2 Answers

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))
like image 148
Kevin Avatar answered Sep 18 '22 05:09

Kevin


Making tdelaney's answer formal and demonstrating the difference...

Strings

#test.py
import traceback

try :
    raise TypeError("Wrong Type baby!")

except Exception as e:
    print( "EXCEPTION FORMAT PRINT:\n{}".format( e ) )
    print( "EXCEPTION TRACE  PRINT:\n{}".format( "".join(traceback.format_exception(type(e), e, e.__traceback__))

Resulting console output

EXCEPTION FORMAT PRINT:
Wrong Type baby!
EXCEPTION TRACE  PRINT:
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise TypeError("Wrong Type baby!")
TypeError: Wrong Type baby!

Logging

If you're in the context of logging there's also the exception method and exc_info kwarg that will do the formatting for you. We should note that the debug and info level log messages are ignored out on account of the root logger holding warning as its default log level.

# logTest.py
import logging

try :
    raise ValueError("my bad value")
except Exception as e :
    logging.exception( e )
    logging.debug("\n{}\nDEBUG LEVEL EXAMPLE".format('-'*30), exc_info=e)
    logging.info("\n{}\nINFO LEVEL EXAMPLE".format('-'*30), exc_info=e)
    logging.warning("\n{}\nWARNING LEVEL EXAMPLE".format('-'*30), exc_info=e)
    logging.error("\n{}\nERROR LEVEL EXAMPLE".format('-'*30), exc_info=e)

with the resulting console output...

ERROR:root:my bad value
Traceback (most recent call last):
  File "/Users/me/logTest.py", line 5, in <module>
    raise ValueError("my bad value")
ValueError: my bad value
WARNING:root:
------------------------------
WARNING LEVEL EXAMPLE
Traceback (most recent call last):
  File "/Users/me/logTest.py", line 5, in <module>
    raise ValueError("my bad value")
ValueError: my bad value
ERROR:root:
------------------------------
ERROR LEVEL EXAMPLE
Traceback (most recent call last):
  File "/Users/me/logTest.py", line 5, in <module>
    raise ValueError("my bad value")
ValueError: my bad value
like image 22
jxramos Avatar answered Sep 22 '22 05:09

jxramos