11. Python from beginner to proficient - exception handling and program debugging

Table of contents

Exception overview

There are four main exception handling statements

Program debugging: Python has two common debugging methods


Exception overview

Exception: An exception is an error that occurs and interrupts the normal execution of the program.

There are four main exception handling statements

Example library: Exception occurs when inputting floating point number or divisor is 0

def division():
    '''功能:分苹果'''
    print("\n===================== 分苹果了 =====================\n")
    apple = int(input("请输入苹果的个数:"))        # 输入苹果的个数
    children = int(input("请输入来了几个小朋友:")) 
    result = apple//children                        # 计算每人分几个苹果
    remain =apple-result*children                   # 计算余下几个苹果
    if remain>0:
        print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,
              "个,剩下",remain,"个。")
    else:
        print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。")
if __name__ == '__main__':
    division()                                      # 调用分苹果的函数

1. try...except: can catch exceptions and give corresponding processing results

    grammar:

        try:

            block1 #Put in code that may generate exceptions

        except [ExceptionName [as alias]]   

                #[ExceptionName [as alias]]: Specify the exception to be handled. If not specified, all exceptions will be handled.

                #[as alias]: Specify an alias for the exception, which can be represented by the alias when outputting the exception content

            block2 #Put the processing results in. If an exception occurs in block1, the code in block2 will be executed.

Example

def division():
    '''功能:分苹果'''
    print("\n===================== 分苹果了 =====================\n")
    apple = int(input("请输入苹果的个数:"))                     # 输入苹果的个数
    children = int(input("请输入来了几个小朋友:"))
    if apple < children:
        raise ValueError("苹果太少了,不够分...")
    result = apple // children                                   # 计算每人分几个苹果
    remain = apple - result * children                          # 计算余下几个苹果
    if remain > 0:
        print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result,
              "个,剩下", remain, "个。")
    else:
        print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。")
if __name__ == '__main__':
    try:                                                           # 捕获异常
        division()                                                 # 调用分苹果的函数
    except ZeroDivisionError:                                      # 处理除数为0的异常
        print("\n出错了 ~_~ ——苹果不能被0个小朋友分!")
    except ValueError as e:                                        # 处理值为浮点数的异常
        print("\n出错了 ~_~ ——",e)

#也可以一次指定多个异常
# if __name__ == '__main__':
#     try:                                        # 捕获异常
#         division()                              # 调用分苹果的函数
#     except (ZeroDivisionError,ValueError) as e:                   # 处理异常
#         print(e)

2. try...except ...else: handle the situation where no exception occurs when catching the exception.

    grammar:

        try:

            block1

        except [ExceptionName [as alias]]   

            block2

        else:

            block3 #Execute only when no exception is thrown

Example        

def division():
    '''功能:分苹果'''
    print("\n===================== 分苹果了 =====================\n")
    apple = int(input("请输入苹果的个数:"))                     # 输入苹果的个数
    children = int(input("请输入来了几个小朋友:"))
    if apple < children:
        raise ValueError("苹果太少了,不够分...")
    result = apple // children                                   # 计算每人分几个苹果
    remain = apple - result * children                          # 计算余下几个苹果
    if remain > 0:
        print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result,
              "个,剩下", remain, "个。")
    else:
        print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。")
if __name__ == '__main__':
    try:                                        # 捕获异常
        division()                              # 调用分苹果的函数
    except (ZeroDivisionError,ValueError) as e:                   # 处理异常
        print(e)
    else:
        print("分苹果顺利完成..")  #代码执行正常后再执行

3. try...except finally #Whether there is an exception or not, a fixed code must be executed

    In actual project development, it is often used to implement operations related to closing, such as closing files

    grammar:

        try:

            block1

        except [ExceptionName [as alias]]   

            block2

        finally:

            block3    

Example

def division():
    '''功能:分苹果'''
    print("\n===================== 分苹果了 =====================\n")
    apple = int(input("请输入苹果的个数:"))                     # 输入苹果的个数
    children = int(input("请输入来了几个小朋友:"))
    if apple < children:
        raise ValueError("苹果太少了,不够分...")
    result = apple // children                                   # 计算每人分几个苹果
    remain = apple - result * children                          # 计算余下几个苹果
    if remain > 0:
        print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result,
              "个,剩下", remain, "个。")
    else:
        print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。")
if __name__ == '__main__':
    try:                                        # 捕获异常
        division()                              # 调用分苹果的函数
    except (ZeroDivisionError,ValueError) as e:                   # 处理异常
        print(e)
    else:
        print("分苹果顺利完成..")
    finally:
        print("进行了一次分苹果操作")

4. Use the raise statement to throw an exception

    During program development, if a function or method may generate an exception, but we do not want to handle the exception in the current function or method, we can use the raise statement to throw an exception in this function or method. After the exception is thrown, The following code will not be executed again

    grammar:

        raise [ExceptionName[(reason)]]

                #[ExceptionName[(reason)]]: Define the name of the exception thrown. If this parameter is omitted, the current error will be thrown unchanged.

                #[(reason)]: Description of the exception information. If this parameter is omitted, no description information will be attached when the exception is thrown.

       Example: Simulate kindergarten to distribute apples (everyone gets at least one) otherwise an exception will be thrown

def division():
    '''功能:分苹果'''
    print("\n===================== 分苹果了 =====================\n")
    apple = int(input("请输入苹果的个数:"))                  
    children = int(input("请输入来了几个小朋友:"))
    if apple < children:
        raise ValueError("苹果太少了,不够分...")
    result = apple // children                                
    remain = apple - result * children                          
    if remain > 0:
        print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result,
              "个,剩下", remain, "个。")
    else:
        print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。")
if __name__ == '__main__':
    try:                                       
        division()                            
    except (ZeroDivisionError,ValueError) as e:              
        print(e)

Program debugging: Python has two common debugging methods

Breakpoint: When debugging and running a program, set a breakpoint wherever you want the program to stop. Multiple breakpoints can be set in one program.

(1) Use IDLE that comes with python for program debugging

    Turn on debugging:

        Open IDLE → Debug → Debugger

    The role of the debug console button:

        Globals: display global variables

        Go: continue execution

        Step: If other functions are called at the set breakpoint, then this button will enter the internal execution of the function.

        Over: single step execution

        Out: The jump out function corresponds to the Step

        Quit: End debugging and modify

    Set breakpoint:

        Place the cursor on the line where you want to set a breakpoint, right-click the mouse and select SetBreaKpoint

        After setting the breakpoint, press F5 to execute the code for debugging.    

(2) Use assert statement to debug the program

    It is generally used to verify the conditions that the program must meet at a certain moment, and is generally used in combination with exception handling statements

    It cannot be used to check user input, it can only be used to check whether something is always true, if it cannot be guaranteed, there is a bug in the program. This is because the assert statement is only valid during debugging. You can turn off the assert statement through python -O filename.py when executing the python command on the command line.

    python -O filename.py: Indicates executing statements in non-debugging state

    grammar:

        assert expression [,reason]

                #expression: Expression to satisfy the condition, if it is false, throw False: AssertionError exception

                #[,reason]: Describe the judgment conditions to better clarify the cause of the problem

    Example

def division():
    '''功能:分苹果'''
    print("\n===================== 分苹果了 =====================\n")
    apple = int(input("请输入苹果的个数:"))          
    children = int(input("请输入来了几个小朋友:"))
   
    assert apple > children ,"苹果不够分"    #应用断言调试
    
    result = apple//children                
    remain =apple-result*children                 
    if remain>0:
        print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,
               "个,剩下",remain,"个。")
    else:
        print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。")
if __name__ == '__main__':
    division()                   
    
    # 将assert语句和异常处理语句结合使用时,删除上面的division()语句,然后打开下面4行代码的注释
##    try:
##        division()                                    # 调用分苹果的函数
##    except AssertionError as e:
##        print("\n输入有误:",e)

Guess you like

Origin blog.csdn.net/weixin_43812198/article/details/131221773