当前位置:网站首页>Lesson 033: exception handling: you can't always be right 2 | after class test questions and answers
Lesson 033: exception handling: you can't always be right 2 | after class test questions and answers
2022-06-22 21:36:00 【ChaseTimLee】
Test questions :
0. What methods do we use to handle the exceptions in the program ?
answer : Use try……except Collocation to catch exceptions in handlers .
try:
Detection range
except Exception[as reason]:
Something unusual happened (Exception) Post processing code
1. One try Statements can be combined with multiple except Sentence collocation ? Why? ?
answer : Sure . because try There may be many kinds of exceptions in the statement block , Using multiple except Statements can respectively catch and handle the exceptions we are interested in .
try:
sum = 1 + '1'
f = open(' I am a nonexistent document .txt')
print(f.read())
f.close()
except OSError as reason:
print(' File error T_T\n The reason for the error is that :' + str(reason))
except TypeError as reason:
print(' Wrong type T_T\n The reason for the error is that :' + str(reason))
2. Do you know how to handle multi class exceptions in a unified way ?
answer : stay except Use parentheses after “()” Enclose multiple exceptions that need to be handled uniformly :
try:
int('abc')
sum = 1 + '1'
f = open(' I am a nonexistent document .txt')
print(f.read())
f.close()
except (OSError, TypeError):
print(' Error T_T\n The reason for the error is that :' + str(reason))
3. except If there is no exception class in the back ,Python Will capture all (try In the block ) And handle them uniformly , But the little turtle doesn't recommend this , Do you know why ?
answer : Because it will hide all the errors that programmers did not think of and were not prepared to deal with , For example, user input ctrl+c Attempting to terminate the program will be interpreted as KeyboardInterrupt abnormal .
4. If the exception occurs after successfully opening the file ,Python Jump to the except Statement execution , Did not execute command to close file ( The data written to the file by the user may not be saved ), So we need to make sure that in any case ( Even if there is an abnormal exit ) The file will also be closed , What should we do ?
answer : We can use finally Statement to implement , If try There are no runtime errors in the statement block , Will skip except Statement block execution finally The content of the statement block .
If there is an anomaly , It will be executed first except The contents of the statement block are then executed finally The content of the statement block . All in all ,finally The content in a statement block is what ensures that it will be executed anyway !
5. Please restore the contents blocked by mosaic in the following code , After the program is executed, it can be output as required .
Code :
Output 
try:
for i in range(3):
for j in range(3):
if i == 2:
raise KeyboardInterrupt
print(i, j)
except KeyboardInterrupt:
print(' Quit !')
use one's hands :
0. Remember our first little game ? As long as the user enters non integer data , The program will immediately pop up the discordant exception information and crash . Please use the exception handling method just learned to modify the following program , Improve user experience .
Guess number games :
import random
secret = random.randint(1,10)
print('------------------ I love fish C Studio ------------------')
temp = input(" Guess which number the little turtle is thinking about now :")
guess = int(temp)
while guess != secret:
temp = input(" Oh dear , Wrong guess. , Please re-enter it :")
guess = int(temp)
if guess == secret:
print(" what the fuck , Are you a worm in the heart of little turtle ?!")
print(" hum , There's no reward for a good guess !")
else:
if guess > secret:
print(" Brother , Big, big ~~~")
else:
print(" well , The small , The small ~~~")
print(" Game over , Don't play ^_^")
answer : Here is a description of the guess = int(temp) Monitoring
import random
secret = random.randint(1,10)
print('------------------ I love fish C Studio ------------------')
temp = input(" Guess which number the little turtle is thinking about now :")
try:
guess = int(temp)
except ValueError:
print(' Input error !')
guess = secret
while guess != secret:
temp = input(" Oh dear , Wrong guess. , Please re-enter it :")
guess = int(temp)
if guess == secret:
print(" what the fuck , Are you a worm in the heart of little turtle ?!")
print(" hum , There's no reward for a good guess !")
else:
if guess > secret:
print(" Brother , Big, big ~~~")
else:
print(" well , The small , The small ~~~")
print(" Game over , Don't play ^_^")
1. input() Functions can produce two types of exceptions :EOFError( end of file endoffile, When the user presses the key combination Ctrl+d produce ) and KeyboardInterrupt( Cancel input , When the user presses the key combination Ctrl+c produce ), Modify the above code again , Capture processing input() Two types of exceptions , Improve user experience .
import random
secret = random.randint(1,10)
print('------------------ I love fish C Studio ------------------')
try:
temp = input(" Guess which number the little turtle is thinking about now :")
guess = int(temp)
except (ValueError, EOFError, KeyboardInterrupt):
print(' Input error !')
guess = secret
while guess != secret:
temp = input(" Oh dear , Wrong guess. , Please re-enter it :")
guess = int(temp)
if guess == secret:
print(" what the fuck , Are you a worm in the heart of little turtle ?!")
print(" hum , There's no reward for a good guess !")
else:
if guess > secret:
print(" Brother , Big, big ~~~")
else:
print(" well , The small , The small ~~~")
print(" Game over , Don't play ^_^")
2. Try a new function int_input(), When the user enters an integer, it returns normally , Otherwise, an error will be prompted and re input is required .
The program implementation is shown in the figure :

def int_input(prompt=''):
while True:
try:
int(input(prompt))
break
except ValueError:
print(' error , You are not entering an integer !')
int_input(' Please enter an integer :')
3. Close the file and put it in finally There will still be problems executing in the statement block , Like the code below , Does not exist in the current folder "My_File.txt" This file , So what happens when the program executes ? Do you have a way to solve this problem ?
try:
f = open('My_File.txt') # Does not exist in the current folder "My_File.txt" This file T_T
print(f.read())
except OSError as reason:
print(' Error :' + str(reason))
finally:
f.close()
answer : because finally Statement block trying to close a file that has not been successfully opened , Therefore, an error will pop up, as follows :
>>> Error :[Errno 2] No such file or directory: 'My_File.txt'
Traceback (most recent call last):
File "C:\Users\FishC000\Desktop\test.py", line 7, in <module>
f.close()
NameError: name 'f' is not defined
Let's fix it this way :
try:
f = open('My_File.txt') # Does not exist in the current folder "My_File.txt" This file T_T
print(f.read())
except OSError as reason:
print(' Error :' + str(reason))
finally:
if 'f' in locals(): # If the file object variable has the current local variable symbol table , It indicates that it was opened successfully
f.close()
边栏推荐
- ACM. HJ45 名字的漂亮度 ●●
- [redis]配置文件
- 94-SQL优化案例一则(用到的写法经常是被嫌弃的)
- 5分钟快速上线Web应用和API(Vercel)
- When the AUX1 or aux2 channel is used in Jerry's aux mode, the program will reset the problem [chapter]
- 第022讲:函数:递归是神马 | 课后测试题及答案
- 第032讲:异常处理:你不可能总是对的 | 课后测试题及答案
- 84- I am on Internet & lt; 52 SQL statement performance optimization strategies & gt; Some views of
- ACM. Hj24 chorus ●●
- LeetCode#20. Valid parentheses
猜你喜欢

分享insert into select遇到的死锁问题(项目实战)

Lesson 014-15: string (see lesson 27-32 of the new version of little turtle) | after class test questions and answers

300. 最长递增子序列 ●●

How swiftui simulates the animation effect of view illumination increase
![Jerry's music mode obtains the directory of playing files [chapter]](/img/2f/efb8a077e3e398cb3b14cfd98a8422.png)
Jerry's music mode obtains the directory of playing files [chapter]

第018讲:函数:灵活即强大 | 课后测试题及答案

RealNetworks vs. 微软:早期流媒体行业之争

杰理之开启四声道通话近端变调问题【篇】

2022化工自动化控制仪表考试练习题及在线模拟考试

One line of code binds swiftui view animation for a specific state
随机推荐
las 点云创建网格
[redis]Redis6的事务操作
[142. circular linked list II]
第030讲:文件系统:介绍一个高大上的东西 | 课后测试题及答案
Share deadlock problems encountered in insert into select (project practice)
300. 最长递增子序列 ●●
Simulated 100 questions and simulated examination of hoisting machinery command examination in 2022
Lesson 018: function: flexible is powerful after class test questions and answers
基于C语言开发工资管理系统 课程论文+源码及可执行exe文件
Japanese anime writers and some of their works
Lesson 016: sequence | after class test questions and answers
RuntimeError: CUDA error: CUBLAS_STATUS_EXECUTION_FAILED when calling `cublasSgemmStridedBatched( ha
[redis]redis persistence
快速排序模板 & 注意事项
[redis]redis的持久化操作
什么是数据资产?数据资产管理应该如何落地?
第016讲:序列 | 课后测试题及答案
Jerry's music mode obtains the directory of playing files [chapter]
软考必备资料大放送,全科目软考资料都给你备好了!
85- have you learned any of these SQL tuning tips?