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"
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.
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.
There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
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.
If your exception object is exc
, then:
type(exc).__name__
.str(exc)
.So you can just do this:
print('{}: {}'.format(type(exc).__name__, exc))
Making tdelaney's answer formal and demonstrating the difference...
#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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With