Use try...except... program structure in python to get exception information, as shown below:
try:
...
except Exception as e:
...
1. The usage of str, repr, traceback
1. str(e)
returns a string type, only the exception information is given, excluding the type of the exception information, such as 1/0 of the exception information'division
by zero'
2. repr(e)
gives more complete exception information, Including the type of exception information, such as the exception information
"ZeroDivisionError('division by zero')" of 1/0.
3. The traceback module
needs to be imported to use the traceback module. At this time, the information obtained is the most complete, and an error message appears when running the program with the python command line. Unanimous. Use traceback.print_exc() to print the exception information to standard error as if it was not obtained, or use traceback.format_exc() to obtain the same output as a string. You can also pass various parameters to these functions to limit the output, or reprint to objects like file types.
try:
1/0
except Exception as e:
print('str(e):\t', str(e))
print("repr(e):\t", repr(e))
import traceback
try:
1/0
except Exception as e:
print('traceback.print_exc():\n%s' % traceback.print_exc())
import traceback
try:
1/0
except Exception as e:
print('traceback.format_exc():\n%s' % traceback.format_exc())
2. The difference between python2 and 3
(1) In the except clause of Python 3 Exception, the use of a comma',' to separate Exception and e is not supported, so you need to use the as keyword to replace
The following writing methods are supported in python2, but not in python3
try:
...
except Exception, e:
...
(2) There is the usage of e.message in python2, and the information obtained is the same as str(e)
as follows:
try:
1/0
except Exception as e:
print("e.message:", e.message)
Results of the:
('e.message:', 'integer division or modulo by zero')
The Python 3 Exception class does not have a message member variable. When python23 is switched, it is replaced with str(e) for compatibility.