Home  >  Article  >  Backend Development  >  How to implement exception handling mechanism in Python automated testing?

How to implement exception handling mechanism in Python automated testing?

WBOY
WBOYforward
2023-05-07 21:10:10832browse

    1. Foreword

    Mainly explains the knowledge points related to the introduction, capture and processing of exceptions in Python

    2. Exception handling collection

    2.1 Explanation of Exception Handling

    Before we formally introduce exception handling, we need to first understand a concept: programming is impossible to be perfect, and there are always situations that cannot be considered, because no one is perfect. Humans, humans are flawed, not to mention that programming is done by humans. In real projects, don’t believe what anyone says: My code is perfect, and there will definitely be no problems with this. In similar words, you must know the meaning of programming. In this world, there is no absolute reliability.

    Everyone should also be aware that as long as the program is written by people, there will definitely be problems. If the program does not execute according to the normal process, we call it an exception. Exception handling, as the name suggests, is to solve this abnormal situation. It allows the program to execute normally according to logic and flow.

    2.2 Exception capture

    When a program executes and reports an error, it will terminate its operation. If we run the exception again after handling the exception, there will be no more errors. Being able to capture this error will allow the program to run smoothly. This The process of exception handling is called exception catching. Let us first look at an example:

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

    How to implement exception handling mechanism in Python automated testing?

    As shown in the above code, when the input data is 18, it can proceed normally The program's logical calculations allow the code to 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. The literal meaning is to tell us that a numerical error has occurred and the string cannot be converted to an integer:

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

    How to implement exception handling mechanism in Python automated testing?

    As shown in the picture above, when a ValueError error 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("恭喜您符合注册条件")

    How to implement exception handling mechanism in Python automated testing?

    As shown in the picture above As shown in the figure, we execute the program again and enter abc. The program still cannot run. It is no longer the ValueError error reported just now. The current error report is a TypeError error.

    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 in the context of the current program Make a mark, and return to the mark when an exception occurs. The try clause is executed first, and subsequent scenarios may occur:

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

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

    Scenario 3: If no exception occurs when the try clause is executed, Python will continue to execute the code statement.

    After we understand the principle of exception capture, let’s take a look at how to solve the previous TypeError error. The literal meaning is that the type is wrong. Integers cannot be compared with strings, but in fact we have already done this before. The variable age is processed, but because the try exception is captured, the first except clause matching try is executed, and the clause replaces the exception statement, so the type conversion here is invalid, and the program is run again. A type error will occur, and the solution is very simple. You only need to put the judgment statement in try.

    When the judgment statement is placed in try, it changes slightly. If no exception is caught, the program will execute as usual and the judgment will take effect. If an exception is caught, it will jump directly to the except execution output and prompt you. If the age is illegal, there will be no judgment logic, so TypeError errors will not occur. 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("您的年龄输入非法,请重新运行本程序")

    How to implement exception handling mechanism in Python automated testing?

    How to implement exception handling mechanism in Python automated testing?

    How to implement exception handling mechanism in Python automated testing?

    ##2.4 Specific exception capture

    Specific exception capture, as the name implies, is to target a certain Catch a specific exception that occurs, such as the ValueError we encountered. If you catch other exception types, an error will still occur if a ValueError is encountered when the code is executed:

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

    How to implement exception handling mechanism in Python automated testing?

    当捕获的类型错误时,仍然会弹出报错终止程序运行,好比一个人酒驾,那么就应该由交警处理而不是民政局的人处理,因为那不是它的职责,异常捕获还要讲究对口,如下代码所示,如果设置成ValueError就能够成功进行捕获,就好比交警处理了酒驾一样,完美解决:

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

    How to implement exception handling mechanism in Python automated testing?

    2.5 异常捕获的处理

    刚刚我们举了一个例子,当异常捕获为IndexError时,运行程序后仍然会出现ValueError的错误,但我们不设置直接使用except时反而能直接捕获,那我们还要设置它做什么呢?想必有部分同学心中已经会产生这样的疑问了。

    except可以理解为万能警察,万能捕手,它可以捕获所有的异常类型(极少数无法直接捕获),而特定的异常捕获只能捕获特定出现的异常情况,我们之所以还要使用,是因为它是专门捕获一种类型的,好比一个人有皮肤问题,那么肯定是挂皮肤科门诊要比急诊科的医生要更加专业,正所谓术业有专攻。

    except因为是万能捕手,所以它在抓获异常后的处理方式是一样的,好比感冒和心脏病发作两种症状,都是同样的对待方式显然是不合理的,那么这个时候就会由特定的“医生” (特定捕获) 进行对应的处理方式。

    目前常见的一些报错有:ValueError、TypeError、IndexError等等,那么在整个自动化测试的过程中,势必会遇到很多其他的报错,当我们不清楚其他报错的情况下如何进行异常捕获呢?两种方式,第一种是错过一次就记得了,好比一开始进行编程的小伙伴们,谁也不知道会遇到ValueError一样,当碰到过一次后,下一次就会特别注意这个事情,提前做一个捕获,俗称踩坑。那另外一种方式就是在末尾继续添加except,万能捕手我们也留着,这样当特定捕获没有捕获到异常但程序出现了异常时,except就会进行捕获:

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

    How to implement exception handling mechanism in Python automated testing?

    2.6 except、Exception与BaseException

    except我们知道了是万能捕手,但其实它的身份是Exception,Python默认帮我们省略了,实际上它是这样的:

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

    except与except Exception完全等价,日常的编写时可加可不加,依据个人习惯和喜好决定即可。而BaseException是Exception的父类,作为子类的Exception无法截获父类BaseException类型的错误。

    BaseException: 包含所有built-in exceptions

    Exception: 不包含所有的built-in exceptions,只包含built-in, non-system-exiting exceptions,像SystemExit类型的exception就不包含在其中。Python所有的错误都是从BaseException类派生的

    2.7 finally用法

    finally的作用是无论except是否成功捕获到了对应的异常,均需要执行finally下的代码:

    """
    参考如下代码:打开了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 异常信息的打印输出

    虽然我们能够捕获异常,但我们肯定要了解到底是什么异常,在捕获到一个异常时我们可以进行异常信息的打印:

    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}")

    How to implement exception handling mechanism in Python automated testing?

    刚刚有提到except与except Exception是等价的,但是如果想使用as必须要使用后者,这是语法规定:

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

    The above is the detailed content of How to implement exception handling mechanism in Python automated testing?. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete