python3_ abnormal && pass sentence

Use the exception object to manage errors that occur during the execution of the program.
Abnormal try-except block is processed.

1 Introduction

  • Find the abnormal
print(5/0)

Here Insert Picture Description

  • Abnormal grammar explanations:
    the error-prone code in a try statement run,
    if there is no error: skip the contents of the statement except to run the other remaining code.
    If errors are reported: one by one to find the error corresponding to the type of back except, 1. Find the corresponding error in this block of code error. Running the residual block. 2. The corresponding error is not found, an error does not run the remaining code block.
  • example:
try:
	print(5/0)
except ZeroDivisionError:
	print("除数不能为0")

2.else code block:

Use the else block is the role only if the statement is not being given time, will execute the print statement.
If you do not use the else statement, print statement executes regardless of the error or not being given.

try:
	要测试的语句
except 异常类型:
	引发异常后的操作
else:
	没引发异常时的操作 

EG:
1. Divisor can not be zero anomalies

try:
	result = 6/2
except ZeroDivisionError:
	print("除数不能为o")
else:
	print(result) #不引发异常时时,才执行。
print("程序执行完毕!") #不管是否引发异常都会执行。

2. File not found abnormal

try:
	with open('file.txt') as f:
		content = f.read()
except FileNotFoundError:
	print("文件找不到")
else:
	print("问价内容是:"+content)

3. Example: Text Analysis

def count_words(filename):
"""计算一个文件大致包含多少个单词"""
	try:
		with open(filename) as f:
			contents = f.read()
	except FileNotFoundError:
		msg="sorry,the file"+filename+"does not exist."
		print(msg)
	else:
		#计算文件大致包含多少个单词
		words = contents.split() #以空格分割文本,生成列表。
		numbers = len(words)
		print("the file "+filename+"has about"+str(numbers)+"words.")
	filenames = ['a1.txt','a2.txt','a3.txt','a4.txt'] #其中有的文件不存在,也不影响程序。
	for filename in filenames:
		count_words(filename) 

4.pass statement

The pass statement expressed do nothing, can also act as a placeholder.

a = 2
if a == 2:
    print("a是2")
else:
    pass
print("it is over!")
Published 80 original articles · won praise 0 · Views 1736

Guess you like

Origin blog.csdn.net/weixin_41272269/article/details/104534054