当前位置:网站首页>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 :
Alt
Output Alt

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 :

Alt

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()


原网站

版权声明
本文为[ChaseTimLee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222005193702.html