Learning python (17)-exception mechanism handling

0. Programming error

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 grammatical 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. Runtime error, that is, the program is grammatically correct, but an error occurs during runtime.

Exception type meaning
AssertionError When the condition after the assert keyword is false, the program will stop and throw an AssertionError exception
AttributeError Exception thrown when the object attribute you are trying to access does not exist
IndexError Index out of sequence range will raise this exception
KeyError This exception is raised when looking up a non-existent keyword in the dictionary
NameError This exception is thrown when trying to access an undeclared variable
TypeError Invalid operation between different types of data
ZeroDivisionError In the division operation, the divisor is 0 and this exception is raised

When an abnormality occurs in a program, it means that an abnormal situation occurred during the execution of the program and cannot be executed anymore. By default, 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. Developers can use exception handling to fully control their programs. Exception handling can not only manage the normal process operation, but also deal with the program when it goes wrong. Greatly improve the robustness of the program and the friendliness of human-computer interaction.

1. Exception handling

In Python  , use try exceptstatement blocks to catch and handle exceptions. The basic syntax structure is as follows:

try:
    Code block that may produce exceptions
except [(Error1, Error2, ...) [as e] ]:
    Code block 1 for handling exceptions
except [(Error3, Error4, ...) [as e] ]:
    Handling exceptions Code block 2
except [Exception]:
    handle other exceptions

In this format, the part enclosed in [] can be used or omitted. The meaning of each part is as follows:

  • (Error1, Error2,...), (Error3, Error4,...): Among them, Error1, Error2, Error3 and Error4 are specific exception types. Obviously, an except block can handle multiple exceptions at the same time.
  • [as e]: As an optional parameter, it means to give the exception type an alias e. The advantage of this is that it is convenient to call the exception type in the except block (will be used later).
  • [Exception]: As an optional parameter, it can refer to all exceptions that may occur in the program, and it is usually used in the last except block.

It try exceptcan be seen from the basic syntax format that there is one and only one try block, but there can be multiple except code blocks, and each except block can handle multiple exceptions at the same time. When different unexpected situations occur in the program, it will correspond to a specific exception type, and the Python interpreter will select the corresponding except block according to the exception type to handle the exception.

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

  1. First execute the code block in try. 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 a suitable except block is found, 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 that handles 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 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.

In fact, each type of exception provides the following properties and methods. By calling them, you can obtain information about the type of exception currently handled:

  • args: returns the error number and description string of the exception;
  • str(e): returns exception information, but does not include the type of exception information;
  • repr(e): Return more complete exception information, including the type of exception information.

On try exceptthe basis of the original structure, the Python  exception handling mechanism also provides an else block, which is to add an else block to the original try except statement, that is, the try except elsestructure. The code wrapped with else will be executed only when the try block does not catch any exceptions; on the contrary, if the try block catches the exception, even if the corresponding except is called to handle the exception, the code in the else block will not be executed. .

The Python  exception handling mechanism also provides a finally statement, which is usually used to clean up the program in the try block. Note that, unlike the else statement, finally is only required to be used in conjunction with try. As for whether the structure contains except and else, it is not necessary for finally (else must be used in conjunction with try except).

In the entire exception handling mechanism, the function of the finally statement is: no matter whether an exception occurs in the try block, it will eventually enter the finally statement and execute the code block in it. Based on this characteristic of the finally statement, in some cases, when the program in the try block opens some physical resources (files, database connections, etc.), these resources must be manually recycled, and the recycling work is usually placed in the finally block in. The Python garbage collection mechanism can only help us reclaim the memory occupied by variables and class objects, but cannot automatically complete tasks such as closing files and database connections.

Program running abnormalities caused by errors need to be solved by the programmer; but there are some exceptions, which are the result of the normal operation of the program, such as exceptions manually raised by raise. The basic grammatical format of the raise statement is:

raise [exceptionName [(reason)]]

Among them, the parameters enclosed in [] are optional parameters, which are used to specify the name of the exception thrown and the description of the exception information. If all optional parameters are omitted, raise will throw the current error as it is; if only (reason) is omitted, no exception description information will be attached when an exception is thrown. In other words, the raise statement has the following three common uses:

  1. raise: A single raise. This statement raises an exception caught in the current context (for example, in an except block), or by default it raises a RuntimeError exception.
  2. Raise exception class name: raise with an exception class name, which means that an exception of the execution type is raised.
  3. Raise exception class name (description information): When raising a specified type of exception, attach the description information of the exception.

In the process of actually debugging a program, sometimes it is not enough to only obtain the type of the exception, and more detailed exception information is needed to solve the problem. When catching an exception, there are two ways to get more exception information, namely:

  1. Use the exc_info method in the sys module;
  2. Use the related functions in the traceback module.

The exc_info() method returns the current exception information in the form of a tuple. The tuple contains 3 elements, namely type, value and traceback. Their meanings are:

  • type: the name of the exception type, which is a subclass of BaseException
  • value: The caught exception instance.
  • traceback: is a traceback object.

In addition to using the sys.exc_info() method to obtain more exception information, you can also use the traceback module, which can be used to view the propagation trajectory of the exception and trace the source of the exception trigger.

Guess you like

Origin blog.csdn.net/qq_35789421/article/details/113663502