How to make the program more robust-exception handling

An exception refers to an error that is caused when the program is running. There are many ways to cause an error, such as dividing by 0, subscript out of range, file non-existence, network abnormality, type error, and so on. An error will cause the program to terminate. If you can use the exception handling structure reasonably, deal with the exceptions that may occur in the program, and convert the python's obscure error prompts into more user-friendly and clearer prompts, you can make the program more robust and more powerful. Fault tolerance.

Python exception class

All exception base classes in python are baseException, and all other exception classes are subclasses inherited from this.
The main exception classes are as follows:

baseException All exception base classes
SystemExit Interpreter request to exit
KeyboardInterrupt User interrupt execution (usually input ^C)
GeneratorExit The generator (generator) has an exception to notify the exit
Exception General error
Warning Warning base class

Python exception handling structure

try except

The most common and basic exception handling structure is the try except structure. The code block after the try is a statement that may cause an exception. The except clause is used to catch the corresponding exception.
If the exception is not caught, then continue to execute; if the exception is caught by the except, the except block is executed; if the exception is not caught, the exception is thrown to the outer layer.
The structure is as follows:

trytryexcept Exception[as reason]: 
    except

For example, the following program requires the user to enter an integer:

while 1 : 
    try : 
        x = int(input('please input a number'))
        break 
    except ValueError: 
        print('this is not a valid number.Try again')
# 运行
please input a number: 'a'
this is not a valid number.Try again

please input a number: 1.5 
this is not a valid number.Try again

please input a number:  1
try except else

Another commonly used exception handling structure is try except else. The difference from the previous structure is: If the try statement does not trigger an exception, the else statement block is executed, and if an exception is thrown, it is not executed.

while 1 : 
    try : 
        x = int(input('please input a integer:'))
    except ValueError: 
        print('this is not a valid number.Try again')
    else:
        print('You\'ve successfully entered an integer')
        break 
#  运行 
please input a integer: 1 
You've successfully entered an integer
try structure with multiple except

The same piece of code may throw multiple exceptions, and you need to deal with different exceptions accordingly. Multiple except blocks support multiple exception capture processing. Multi-branch structure. Once an exception captures an exception, the remaining except Will no longer be executed. (If multiple exceptions may occur, instead of handling them separately, you can write the exceptions in a tuple)

while 1 : 
    try:
        x = input('请输入被除数:')  
        y = input('请输入除数:')
        z = float(x)/float(y)
    except ZeroDivisionError: 
        print('除数不能为0') 
    except ValueError: 
        print('被除数和除数应为数值类型')
    else : 
        print(x,'/',y,'=',z)
        break
#  运行 
请输入被除数:a 
请输入除数:b 
被除数和除数应为数值类型

请输入被除数:1 
请输入除数:2 
1  / 2  = 0.5
try except finally

Another important exception handling structure is try except finally. The statement block in the finally clause will be executed regardless of whether an exception occurs. It is often used to do some clean-up work.

try : 
    f = open('test.txt', 'r')
    line = f.readline()
    print(line)
finally: 
    f.close()

Regardless of whether the reading is abnormal or not, the file must be closed.

Affirmation

The syntax of an assert statement is assert expression [, reason]. When it is judged that the expression expression is true, nothing is done, and if it is false, an exception is thrown.
Assertions are often used to throw custom exceptions, and then used with try except statements;

try: 
    x = float(input('请输入一个正数  :'))
    assert  x>0  
except AssertionError : 
    print('这不是正数')
# 运行
请输入一个正数  : -1 
这不是正数

The above is the python exception class and exception handling structure.
References:
1 Dong Fuguo, Python programming, Tsinghua University Press
2 Novice notes, Python exception handling structure

Guess you like

Origin blog.csdn.net/weixin_43705953/article/details/109538843