Instructions for using python exceptions (python files and exceptions)

abnormal

pyhong uses special objects called exceptions to manage errors that occur during program execution.
Whenever an error occurs that overwhelms python, it creates an exception object. If you write code to handle the exception, the program will continue to run; if you don't handle the exception, the program will stop and display a tracback with a report about the exception.
Exceptions are handled using try-except code blocks. It tells Python what to do when an exception occurs. With it, the program will continue to run even if an exception occurs: display a friendly error message written by you instead of a tracback that confuses the user

1. Handle exception ZeroDivisionError exception

Let's first look at the simple mistakes that cause python exceptions:
you probably know you can't divide a number by 0, but let's make python do it?

print(5/0)

insert image description here
The python interpreter has already told us the error problem during operation.
It said that the division is an error of zero, and the exception object ZeroDivisionError is created when python cannot execute normally according to your requirements.

To fix this, we can use:

2. Use try-except code block

You can write this block of code to handle the exception that might be thrown when you think something might go wrong.

try:
	print(5/0)
except ZeroDivisionError:
	print('零不可以作为除数哦!')

In this code,
we put the code that caused the error in a try block. If the code block at the try does not cause an exception when running, python will not execute the except code block. Instead, python will look for the except code block and execute the code inside it.

Let's take a look at the execution results:
insert image description here

3. Use exceptions to avoid crashes

When an error occurs, it is especially important to handle the error properly if there is still work to be done by the program. This often happens in programs that require user input; if invalid input is properly handled, the user can then be prompted for valid input without crashing.

Let's write a simple calculator:

print('- - - 欢迎使用- 计算器 - - - ')
print('使用请按:'+'e'+',退出请按:'+'q')

while True:
	uInfo = input('请您开始录入:')
	if uInfo == 'q':
		break
	if uInfo =='e':
		number1 = input('请您录入被除数:')
		number2 = input('请您继续录入除数:')
		
		print('计算器正在为您计算结果....')
		print(int(number1)/int(number2))

We just write a simple calculator to illustrate the problems caused by problems with the application program.
If normal programming can do four arithmetic operations, what kind of problems will the only division calculation here cause?
Combining the above knowledge, we know that we need to write a try-except to deal with it. If it is not dealt with, it will cause two problems. One is to reduce the user's sense of use, and try not to let the user experience this kind of incomprehensible The problem. The second is to make it possible for attackers. This kind of problem will lead to your program being attacked by a well-trained attacker. He is likely to get your file name through your traceback.

Below, we deal with this phenomenon through the combined use of else code blocks:

4. else code block

Here we continue to put the code that may cause errors in the try-except code block to improve the program's ability to resist errors. But there is also an else code block included here, and the code that depends on the successful execution of the try code block is placed in the else code block:

print('- - - 欢迎使用- 计算器 - - - ')
print('使用请按:'+'e'+',退出请按:'+'q')

while True:
	uInfo = input('请您开始录入:')
	if uInfo == 'q':
		break
	if uInfo =='e':
		number1 = input('请您录入被除数:')
		number2 = input('请您继续录入除数:')
	
		print('计算器正在为您计算结果....')
		
		try:
			answer = int(number1)/int(number2)
		except ZeroDivisionError:
			print('您不可以输入0作为除数!')
		else:
			print(answer)

In this sample code, we put the lines of code that may cause errors in try. If the program encounters an error during execution, it will prompt the user with the content we have set in advance, instead of displaying unfriendly content that the user cannot understand.
We know that if the program is successfully executed in sequence, it will continue to execute through the try code block, and the calculation result at this time will be output in the code line in the else statement. That is to say, the code statements written in the else code block are all codes that need to be run after the try code block runs successfully.

5. Handle FileNotFoundError exception

What kind of exception will the python interpreter throw if we read a file that doesn't exist?

filename = 'aa.txt'
with open(filename) as file_object:
	contets = file_object.read()

Of course, we did not create this file in advance,
let's take a look at the execution result of this code:
insert image description here
The python interpreter started to report an error,
it displayed a FileNotFoundError exception, it seems that this exception was created because python could not find the file to open .

In fact, this error is caused by open().
It is not difficult to deal with this problem. Remember what we are learning today?
Yes, solved by tey-except code block:

filename = 'aa.txt'

try:
	with open(filename) as file_object:
		contets = file_object.read()
except FileNotFoundError:
	print('很抱歉,您要读取的:'+filename+'文件不存在哦!')

After adding the try code block, after running this code example, if there is still a problem,
it will prompt the user with such information:
insert image description here

In fact, the file to be processed does not exist. So it doesn't make much sense to do it this way. Let's extend this example to see how exception handling can help when you're working with multiple files.

6. Analyzing text

Here I will first introduce a function, split(). It creates a list of words from a string.
What does that mean?

The method split()
splits the string into parts with a space delimiter and stores the parts in a list. The result is a list containing all the words in the string.

Now, we prepare a text file, and
paste the entire content of Hanyaofu inside the text file. Then write code to read this file,
after successful reading, call the split function to separate the elements, and
finally output the separated content to see how many elements we have separated in total:

filename = 'hyf.txt'

try:
	with open(filename) as file_object:
		contets = file_object.read()
		
except FileNotFoundError :
		print('很抱歉,您要读取的:'+filename+'文件不存在哦!')
else:
	words = contets.split()
	num_words = len(words)
	print('本篇文章一共包含段落:'+ str(num_words) +'个。')

In this code, in fact, we do not handle possible exceptions, and the program will not cause errors,
because the text file read by the code exists.

One more thing to explain:
The split() function splits the string based on spaces and stores it as a list.
So executing this code, there are only 7 paragraph lines.

insert image description here

7. Keep silent when you fail

In this title, I want to introduce a pass statement to you.
The try statement used before is all in the except block, which sets the friendly information displayed to the user when an exception occurs,
but what if you don't want to display the content to the user?
We can use the pass statement:

try:
	#省略代码语句
except ZerroDivisionError:
	pass

The except code block written in this way will neither show traceback nor prompt abnormal friendly information content to the user. And the pass statement also acts as a placeholder, which reminds you that you didn't do anything somewhere in the program, and you might want to do something here later.

Guess you like

Origin blog.csdn.net/tianlei_/article/details/129271963