try...except... monitor a piece of code, want to accurately locate the error type and error details
For example, we want to find the fourth value of list a, but it doesn't actually exist...
except Exception as e¶
At this time, just write the code as follows:
a = [1,2,3] try: a except Exception as e: print('error:',e.__class__.__name__) print('error:',e)
Then you will find the output result is as follows:
error: IndexError error: list index out of range
This will accurately return the error type and error details
Use the traceback function to print errors
a = [1,2,3] try: a except Exception as e: traceback.print_exc()
The output error message is as follows:
Traceback (most recent call last): File "<ipython-input-45-d04851f889bb>", line 4, in <module> a IndexError: list index out of range
It can be seen that the error information is more detailed. Precise positioning: error line, error location and error details.
In addition, the error message can be printed out by specifying the location:
a = [1,2,3] try: a except Exception as e: traceback.print_exc(file = open('E:/coding/errorlog_abc.txt','a'))
The console will no longer be displayed, and the result will appear in the specified file: