use try...except block to return the error message accurately

created at 06-27-2021 views: 2

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...

1. Written in the form of except Exception as e

At this time, just write the code as follows:

a = [1,2,3]

try:
    a[3]
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

2. Traceback function of trace module

Use the traceback function to print errors

a = [1,2,3]

try:
    a[3]
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[3]
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[3]
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:

Please log in to leave a comment.