Knowledge Explanation of Exception Handling Mechanism in Python Automated Testing

I. Introduction

Today, the author still wants to talk about the basics in python, mainly explaining the introduction, capture, and processing of exceptions in Python. Only after learning these can we pave the way for the subsequent automated test framework construction and daily maintenance. Let’s go straight to it without talking nonsense. theme it.

Two, exception handling collection

2.1 Exception handling explanation

Before formally introducing exception handling, we need to let everyone understand a concept: programming is impossible to be perfect, and there are always situations that cannot be considered, because no one is perfect, and human beings are flawed, not to mention that programming comes from human beings. Hands, in a real project, don't believe anyone who says: My code is perfect, there will be no problems with this, and similarly, in the world of programming, there is no absolute reliability.

Everyone should also be clear that as long as the program is written by a person, there must be problems. If the program does not execute according to the normal process, we call it an exception. As the name implies, exception handling is to solve this abnormal situation and make the program normally follow the logic. and process execution.

2.2 Exception capture

When a program executes and reports an error, it will stop running. If we run it again after exception handling, there will be no more error reporting. This error report can be caught to make the program run smoothly. This process of exception handling is called exception capture. Let us first look at it one example:

print("------------------- 欢迎来到报名注册系统 -------------------")
 
age = (input("请输入您的年龄:"))
age = int(age)
if age < 18:
    print("很遗憾,您暂时不满足注册条件")
else:
    print("恭喜您符合注册条件")

As shown in the above code, when the input data is 18, the logical calculation of the program can be performed normally, so that the code can be executed normally until the end, but is there really no problem with such code? Let's look at this example again. When the input is abc English letters, a ValueError error occurs , literally telling us that there is a numerical error and the string cannot be converted to an integer:

print("------------------- 欢迎来到报名注册系统 -------------------")
 
age = (input("请输入您的年龄:"))
age = int(age)
if age < 18:
    print("很遗憾,您暂时不满足注册条件")
else:
    print("恭喜您符合注册条件")

As shown in the figure above, when a ValueError occurs, we can handle it through exception capture. The processed code is:

print("------------------- 欢迎来到报名注册系统 -------------------")
age = (input("请输入您的年龄:"))
 
try:
    age = int(age)
except:
    print("您的年龄输入非法,请重新运行本程序")
 
if age < 18:
    print("很遗憾,您暂时不满足注册条件")
else:
    print("恭喜您符合注册条件")

 

As shown in the figure above, we execute the program again and input abc, the program still cannot run, it is not the ValueError just now, but the TypeError now.

2.3 Principle of Exception Capture

To solve the above TypeError error, let's first understand the principle of exception capture. When a try statement is officially started, Python will mark it in the context of the current program. When an exception occurs, return to the mark, and the try clause is executed first. , the following possible scenarios:

Scenario 1: If an exception occurs during the execution of the try statement, Python jumps back to try and executes the first except clause that matches the exception. After the exception is handled, the code continues to execute.

Scenario 2: If an exception occurs during the execution of the try statement, and there is no matching except clause, the exception will be submitted to the upper try or the top layer of the program, and the program will end here, and the error message will be printed.

Scenario 3: If no exception occurs during the execution of the try clause, Python will continue to execute the code statement.

After we understand the principle of exception capture, let's see how to solve the previous TypeError error. The literal meaning is wrong, and the integer cannot be compared with the string, but in fact we have already processed the variable age before that. But because the exception of try is caught, the first except clause matching try is executed, and the clause replaces the exception statement, so the type conversion here is invalid, and a type error will occur when the program is run again. This method is also very simple, just put the judgment statement in the try.

When the judgment statement is placed in the try, it changes a little bit. If no exception is caught, the program will execute as usual, and the judgment will take effect. If an exception is caught, it will directly jump to the except execution output, prompting that your age is illegal, so it will not There will be judgment logic, so there will be no TypeError errors. By the way, this is our common development bug "buy one get one free". The code for the second modification is as follows:

# 程序仍然有可优化的地方,仅展示try.. except语句的使用方式
print("------------------- 欢迎来到报名注册系统 -------------------")
age = (input("请输入您的年龄:"))
 
try:
    age = int(age)
    if age < 18:
        print("很遗憾,您暂时不满足注册条件")
    else:
        print("恭喜您符合注册条件")
except:
    print("您的年龄输入非法,请重新运行本程序")

 

2.4 Specific exception capture

Specific exception capture, as the name implies, is to capture a specific exception that occurs, such as the ValueError we encountered. If you capture other exception types, then when you encounter ValueError during code execution, an error will still be reported:

print("------------------- 欢迎来到报名注册系统 -------------------")
age = (input("请输入您的年龄:"))
 
try:
    age = int(age)
    if age < 18:
        print("很遗憾,您暂时不满足注册条件")
    else:
        print("恭喜您符合注册条件")
# 这里进行捕获的异常类型是IndexError,非ValueError,最后的结果仍然会报错,因为没有成功捕获
except IndexError:
    print("您的年龄输入非法,请重新运行本程序")

When the captured type is wrong, an error message will still pop up to terminate the program. For example, if a person is driving drunk, then it should be handled by the traffic police instead of the Civil Affairs Bureau, because that is not its responsibility. The exception capture should also pay attention to the counterpart, as shown in the following code As shown, if it is set to ValueError, it can be successfully captured, just like the traffic police dealt with drunk driving, perfect solution:

print("------------------- 欢迎来到报名注册系统 -------------------")
age = (input("请输入您的年龄:"))
 
try:
    age = int(age)
    if age < 18:
        print("很遗憾,您暂时不满足注册条件")
    else:
        print("恭喜您符合注册条件")
except ValueError:
    print("您的年龄输入非法,请重新运行本程序")

 

2.5 Handling of exception capture

We just gave an example. When the exception is captured as IndexError, the error of ValueError will still appear after running the program, but we can directly capture it when we don’t set except to use it directly. So what do we need to set it for? Presumably some students have already had such doubts in their minds.

except can be understood as a universal policeman, a universal catcher, which can catch all exception types (very few cannot be directly caught), and specific exception capture can only catch specific exceptions that occur. The reason why we still use it is because it is Specialize in capturing one type. For example, if a person has skin problems, then it must be more professional to go to the dermatology clinic than the doctor in the emergency department. As the saying goes, there is specialization in surgery.

Except because it is a universal catcher, it will deal with it in the same way after catching an exception. For example, it is obviously unreasonable to treat the symptoms of a cold and a heart attack in the same way. Then at this time, a specific " Doctor" (specific capture) for corresponding processing.

At present, some common errors are: ValueError, TypeError, IndexError, etc., so in the whole process of automated testing, we will inevitably encounter many other errors. How to capture exceptions when we are not clear about other errors? There are two ways, the first one is to remember once you miss it, just like the little friends who started programming, no one knows that they will encounter ValueError. After encountering it once, they will pay special attention to it next time. Do a catch in advance, commonly known as stepping on the pit. The other way is to continue to add except at the end, and we also keep the universal catcher, so that when a specific capture does not catch an exception but an exception occurs in the program, except will catch it:

print("------------------- 欢迎来到报名注册系统 -------------------")
age = (input("请输入您的年龄:"))
 
try:
    age = int(age)
    if age < 18:
        print("很遗憾,您暂时不满足注册条件")
    else:
        print("恭喜您符合注册条件")
# 这里会报错ValueError,因为捕获的类型是IndexError,很明显无法进行ValueError异常捕获,那么我们可以在添加一个万能捕手except来进行捕获
except IndexError:
    print("您的年龄输入非法,请重新运行本程序")
# 在下面可以在进行一个except的添加:
except:
    print("万能捕手在此,束手就擒吧!")

 

2.6 except、Exception与BaseException

We know that except is a universal catcher, but in fact its identity is Exception, and Python omits it for us by default. In fact, it looks like this:

except Exception:
    print("万能捕手在此,束手就擒吧!")

except and except Exception are completely equivalent, and can be added or not added in daily writing, depending on personal habits and preferences. BaseException is the parent class of Exception, and Exception as a subclass cannot intercept errors of the parent class BaseException type.

BaseException: Contains all built-in exceptions

Exception: Does not contain all built-in exceptions, only includes built-in, non-system-exiting exceptions, exceptions like SystemExit are not included. All errors in Python are derived from the BaseException class

2.7 usage of finally

The function of finally is to execute the code under finally regardless of whether except successfully captures the corresponding exception:

"""
参考如下代码:打开了love.txt这个文件,进行了阅读,又想写入一点东西,但现在是只读的模式,无法进行内容写入,故此会报错io.UnsupportedOperation
虽然没有写入成功,但是这个文件是成功读取了的,那么在文件的章节中提到过,如果打开了一个文件要记得关闭,否则其他人无法使用
所以在finally这里我们就可以加上f.close(),代表着无论是否有捕捉到异常,最后我都要关闭这个文件,以确保其他人能够正常使用该文件
"""
 
import io
 
try:
    f = open("love.txt", encoding="utf-8", mode="r")
    f.read()
    f.write("随便写点~")
except io.UnsupportedOperation:
    print("抓的就是你这个io.UnsupportedOperation报错")
finally:
    # finally的作用是无论except是否成功捕获到了对应的异常,均需要执行finally下的代码
    f.close()

2.8 Printout of exception information

Although we can catch the exception, we must know what the exception is. When we catch an exception, we can print the exception information:

print("------------------- 欢迎来到报名注册系统 -------------------")
age = (input("请输入您的年龄:"))
 
try:
    age = int(age)
    if age < 18:
        print("很遗憾,您暂时不满足注册条件")
    else:
        print("恭喜您符合注册条件")
# 这里会报错ValueError,捕获的是IndexError,很明显无法进行异常捕获,那么我们可以在添加一个万能捕手except来进行捕获
except IndexError as error:
    print("您的年龄输入非法,请重新运行本程序")
# 在这里加一个as,后面接一个变量,然后进行变量打印即可,当出现对应的异常时就会打印对应异常的信息
except Exception as error:
    print("万能捕手在此,束手就擒吧!", f"已捕获异常:{error}")

It was mentioned just now that except and except Exception are equivalent, but if you want to use as, you must use the latter. This is the grammatical rule:

# 正确用法,在捕获类型后加as 变量
except Exception as error:
    print("万能捕手在此,束手就擒吧!", f"已捕获异常:{error}")
 
# 错误的用法,不符合语法规则
except as error:
    print("万能捕手在此,束手就擒吧!", f"已捕获异常:{error}")

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

insert image description here

Software testing interview applet

The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!

The following interview question sections are covered:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too!     

Guess you like

Origin blog.csdn.net/nhb687095/article/details/132452268