Exceptions, how errors are handled in Python

Developers will inevitably encounter errors when writing programs. Some are grammatical errors caused by the negligence of the writers, some are data errors caused by implicit logic problems in the program, and some are system errors caused by conflicts with the rules of the system when the program is running, etc. Wait.

In general, errors encountered when writing programs can be roughly divided into two categories, namely syntax errors and runtime errors.

Syntax errors, that is, errors that occur when parsing the code. When the code does not conform to the Python grammar rules, the Python interpreter will report a SyntaxError grammatical error during parsing, and at the same time, it will clearly indicate the sentence that detects the error first.

Grammatical errors are mostly caused by the negligence of the developers. They are errors in the true sense and cannot be tolerated by the interpreter. Therefore, the program can only be executed if all grammatical errors in the program are corrected.

However, an abnormal situation occurs during the execution of the program and cannot be executed anymore. This is a runtime error. Runtime errors involve the concept of exceptions.

1. The concept of exception

When the program is running, if the Python interpreter encounters an error, it will stop the execution of the program and prompt some error messages, which is an exception.

By default, if an exception occurs, the program is to be terminated. If you want to prevent the program from exiting, you can use the method of catching the exception to get the name of the exception, and then let the program continue to run through other logic codes. This kind of logic processing based on the exception is called exception processing.

The action of stopping the execution of the program and prompting an error message is usually called: raise an exception.

Abnormal logic diagram

When developing a program, it is difficult to deal with all special cases. Through exception capture, it is possible to centrally deal with emergencies, so as to ensure the stability and robustness of the program.

Two, catch the exception

1. Simple syntax for catching exceptions

In program development, if you are not sure whether the execution of some code is correct, you can add try to catch the exception.

The simplest syntax format for catching exceptions:

try:
    尝试执行的代码
except:
    出现错误的处理

The execution flow of the try except statement is as follows:

  1. First execute the code block in try, which contains the code that is not sure whether it can be executed normally. If an exception occurs during execution, the system will automatically generate an exception type and submit the exception to the Python interpreter. This process is called catching exceptions.

  2. When the Python interpreter receives an exception object, it will look for an except block that can handle the exception object. If it finds a suitable except block, it will hand the exception object to the except block for processing. This process is called exception handling. If the Python interpreter cannot find an except block to handle the exception, the program will terminate and the Python interpreter will exit.

In fact, regardless of whether the program code block is in the try block or even the code in the except block, as long as an exception occurs when the code block is executed, the system will automatically generate the corresponding type of exception. However, if this section of the program is not wrapped with try, or there is no except block configured to handle the exception, the Python interpreter will not be able to process it, and the program will stop running; on the contrary, if the exception that occurs in the program is caught by try and is When the except processing is complete, the program can continue to execute.

Example: Ask the user to enter an integer.

try:
    # 提示用户输入一个数字
    num = int(input("请输入数字:"))
except:
    print("请输入正确的数字")

2. Error type capture

During program execution, different types of exceptions may be encountered, and different types of exceptions need to be responded to. At this time, it is necessary to capture the type of error.

The syntax is as follows:

try:
    # 尝试执行的代码
    pass
except 错误类型1:
    # 针对错误类型1,对应的代码处理
    pass
except (错误类型2, 错误类型3):
    # 针对错误类型2 和 3,对应的代码处理
    pass
except Exception as result:
    print("未知错误 %s" % result)

When the Python interpreter throws an exception, the first word in the last line of the error message is the error type.

An except block can handle multiple exceptions at the same time.

[as …]: As an optional parameter, it means to give an alias to the exception type. The advantage of this is that it is convenient to call the exception type in the except block.

Example: Ask the user to enter an integer.

  1. Prompt the user to enter an integer
  2. Divide 8 by the integer entered by the user and output
try:
    num = int(input("请输入整数:"))
    result = 8 / num
    print(result)
except ValueError:
    print("请输入正确的整数")
except ZeroDivisionError:
    print("除 0 错误")
Catch unknown errors

During development, it is still difficult to predict all possible errors.

If you want the program to not be terminated because the Python interpreter throws an exception regardless of any error, you can add another except.

The syntax is as follows:

except Exception as result:
    print("未知错误 %s" % result)

3. The complete syntax of exception capture

In actual development, in order to be able to handle complex exceptions, the complete exception syntax is as follows:

try:
    # 尝试执行的代码
    pass
except 错误类型1:
    # 针对错误类型1,对应的代码处理
    pass
except 错误类型2:
    # 针对错误类型2,对应的代码处理
    pass
except (错误类型3, 错误类型4):
    # 针对错误类型3 和 4,对应的代码处理
    pass
except Exception as result:
    # 打印错误信息
    print(result)
else:
    # 没有异常才会执行的代码
    pass
finally:
    # 无论是否有异常,都会执行的代码
    print("无论是否有异常,都会执行的代码")

else Code that will be executed only when there is no exception.

Finally, the code will be executed regardless of whether there is an exception.

Example:

try:
    num = int(input("请输入整数:"))
    result = 8 / num
    print(result)
except ValueError:
    print("请输入正确的整数")
except ZeroDivisionError:
    print("除 0 错误")
except Exception as result:
    print("未知错误 %s" % result)
else:
    print("正常执行")
finally:
    print("执行完成,但是不保证正确")

Three, abnormal transmission

Transmission of exceptions-When an exception occurs in the execution of a function/method, the exception will be passed to the caller of the function/method. If it is passed to the main program, there is still no exception handling, the program will be terminated.

In development, you can add exception capture in the main function, and other functions called in the main function, as long as an exception occurs, will be passed to the exception capture of the main function, so there is no need to add a lot of exception capture in the code , To ensure the cleanliness of the code.

Example:

  • Define function demo1() to prompt the user to enter an integer and return
  • Define function demo2() to call demo1()
  • Call demo2() in the main program
def demo1():
    return int(input("请输入一个整数:"))

def demo2():
    return demo1()

try:
    print(demo2())
except ValueError:
    print("请输入正确的整数")
except Exception as result:
    print("未知错误 %s" % result)

Fourth, throw a raise exception

During development, in addition to exceptions thrown by the Python interpreter for code execution errors, exceptions can also be actively thrown according to the specific business requirements of the application.

Example:
Prompt the user to enter the password, if the length is less than 8, throw an exception.
User login exception

The current function is only responsible for prompting the user to enter the password. If the password length is incorrect, other functions are required for additional processing.

Therefore, exceptions can be thrown and caught by other functions that need to be handled.

Throw an exception

Python provides an Exception exception class. During development, if you want to throw an exception when meeting specific business requirements, you can:

  1. Create an Exception object
  2. Use the raise keyword to throw an exception object

We implement the code according to the above requirements:

  • Define the input_password function to prompt the user to enter the password
  • If the user input length <8, throw an exception
  • If the user input length>=8, return the input password
def input_password():

    # 1. 提示用户输入密码
    pwd = input("请输入密码:")

    # 2. 判断密码长度,如果长度 >= 8,返回用户输入的密码
    if len(pwd) >= 8:
        return pwd

    # 3. 密码长度不够,需要抛出异常
    # 1> 创建异常对象 - 使用异常的错误信息字符串作为参数
    ex = Exception("密码长度不够")

    # 2> 抛出异常对象
    raise ex

try:
    user_pwd = input_password()
    print(user_pwd)
except Exception as result:
    print("发现错误:%s" % result)

The pilgrimage of programming

Guess you like

Origin blog.csdn.net/beyondamos/article/details/108355943