Getting exception information is important for program debugging and can help you quickly locate locations with incorrect program statements. Here are some ways to get exception information in Python, where you get the exception (Exception) information using try...except ... Program structure. As shown below
Try: ... except Exception as e: ...
1. STR (e)
Returns the string type, giving only the exception information, excluding the type of exception information, such as 1/0 exception information
' Integer division or modulo by zero '
2, repr (e)
Gives a more complete exception information, including the type of exception information, such as 1/0 exception information
"Zerodivisionerror (' integer division or modulo by Zero ',)"
3, E.message
Information obtained with STR (e)
4. Adopt Traceback Module
The Traceback module needs to be imported, and the information obtained is the most complete, consistent with the error message on the Python command line running the program. Use Traceback.print_exc () to print exception information to a standard error, as if not obtained, or use TRACEBACK.FORMAT_EXC () to get the same output as a string. You can pass a variety of parameters to these functions to limit the output, or to re-print to objects like file types.
Examples are as follows:
Import tracebackprint ' ######################################################## ' print ' 1/0 Exception Info ' print '--- ------------------------------------------------------' try:1/0except Exception as E:print ' str (Exception): \ t ', str (Exception) print ' str (e): \t\t ', str (e) print ' Repr (e): \ t ', repr (e) print ' e.message:\t ', e.message print ' tra Ceback.print_exc (): '; Traceback.print_exc () print ' Traceback.format_exc (): \n%s '% traceback.format_exc () print ' ########################## ############################## ' print ' \n######################################################## ' print ' i = Int (' A ') Exception Info "print '---------------------------------------------------------' try:i = Int (' a ') except Exception a S e:print ' str (Exception): \ t ', str (Exception) print ' str (e): \t\t ', str (e) print ' Repr (e): \ t ', repr (e) print ' E.message:\t ', e.message print ' Traceback.print_exc (): '; Traceback.print_exc () print ' Traceback.format_exc (): \n%s '% traceback.format_eXC () print ' ######################################################## '
Example results
Get Exception (Exception) information in Python