Python exception capture [try...except]

Foreword:

When the code is running, you will often encounter some error reports. Suppose we are processing some file data in batches in a loop. At this time, when a certain piece of data is processed, it is empty, so the system reports an error and terminates the code. At this time, we do not want to ignore this. To report an error, to keep the loop running, exception capture is required.

1. Catching regular exceptions

Basic syntax:

try:
	可能会发生报错的代码
except:
	出现异常后执行的代码

Example:

try:
	# 这里不存在该文件,肯定会报错
	f = open('test.txt','r')
except:
	# 报错后执行该代码,类似于if...else语句,因为w参数在文件不存在时可以自动创建
	f = open('test.txt','w')

2. Catch all exceptions

If we need to see what the content of the error is and the content of the exception caught, use the following method

try:
	f = open('test.txt','r')
except Exception as e:
	print(e)
	

3. Abnormal else

else indicates the code that needs to be executed if there is no exception

try:
	print(123)
except Exception as e:
	print(e)
else:
	print('没有异常执行该代码')

4. Abnormal finally

finally indicates the code to be executed regardless of whether it is abnormal or not, such as closing the file

try:
	f = open('test.txt','r')
except Exception as e:
	f = open('test.txt','w')
else:
	print('没有异常执行该代码')
finally:
	f.close()

Guess you like

Origin blog.csdn.net/modi88/article/details/130332422