Several Methods of Obtaining Exception (Exception) Information by Python

  • 2021-09-05 00:23:43
  • OfStack

Obtaining exception information is very important for program debugging, which can help to quickly locate the position of program statements with errors. The following describes several methods of obtaining exception information in Python, where obtaining exception information (Exception) adopts try … except … program structure.

As shown below:


try:
  print(x)
except Exception as e:
  print(e)

1. str(e)

Returns a string type, giving only exception information, excluding the type of exception information, such as:


try:
  print(x)
except Exception as e:
  print(str(e))

Print results:


name 'x' is not defined

2. repr(e)

Give more complete exception information, including the types of exception information, such as:


try:
  print(x)
except Exception as e:
  print(repr(e))

Print results:


NameError("name 'x' is not defined",)

1 In general, when we know the type of exception information, we can capture exceptions more accurately, such as:


try:
  print(x)
except NameError:
  print('Exception Type: NameError')
except Exception as e:
  print(str(e))

3. Adopt traceback module

Need to import traceback module, at this time to obtain the most complete information, and Python command line running program error message 1.

Usage: Print errors using traceback. print_exc () or traceback. format_exc ().

Difference: traceback. print_exc () is a direct typographical error, traceback.format_exc () returns a string.

Examples are as follows:


import traceback

try:
  print(x)
except Exception as e:
  traceback.print_exc()

Equivalent to:


import traceback

try:
  print(x)
except Exception as e:
  msg = traceback.format_exc()
  print(msg)

The printed results are:


Traceback (most recent call last):
 File "E:/study/python/get_exception.py", line 4, in <module>
  print(x)
NameError: name 'x' is not defined

traceback. print_exc () can also accept file parameters written directly to a file. For example:


#  Write to  tb.txt  In a file 
traceback.print_exc(file=open('tb.txt','w+'))

The above is the Python to obtain exception (Exception) information of several methods in detail, more information about python to obtain exception information please pay attention to other related articles on this site!


Related articles: