SoFunction
Updated on 2024-10-29

Python Exception Handling Mechanism Structure Example Analysis

First, Python's complete exception handling syntax is structured as follows:

try:
  # Business realization code
except Exception1 as e:
  # Exception Handling Block 1
  ...
except Exception2 as e:
  # Exception Handling Block 2
  ...
# There can be more than one except
...
else:
  # Normal processing blocks
finally :
  # Resource recovery blocks
  ...

The execution of the entire exception handling structure is shown in Figure 1.

Note that in the entire exception handling structure, only the try block is required, that is:

  • If there is no try block, there can be no subsequent except block, else block, or finally block. But you can't just use a try block, you can either use a try except structure or a try finally structure;
  • The except block, the else block, and the finally block are all optional, and can be present at the same time;
  • There can be more than one except block, but the except block that catches the parent class exception should follow the except block that catches the child class exception;
  • Multiple except blocks must come after the try block, and the finally block must come after all except blocks.
  • To use an else block, it must be preceded by a try and an except.

Many beginners can't tell the difference between finally and else, so let's focus on that. else blocks are executed only if no exception occurs, while finally statements are executed regardless of whether an exception occurs or not. Not only that, but the finally block executes regardless of whether you exit normally, with an exception, or with a break, continue, or return statement.

Note that if you run a statement in your program that forces you to exit the Python interpreter (such as os._exit(1)), the finally statement will not be executed. For example:

import os
try:
  os._exit(1)
finally:
  print("Execute the finally statement.")

The program runs without any output. Therefore, unless you call a method that exits the Python interpreter in a try block or an except block, the exception-handling finally block will always be executed, no matter what code is executed in the try block or the except block, and no matter what happens.

In addition, in general, do not use statements such as return or raise in the finally block that cause the method to abort (the raise statement will be described later), once the return or raise statement is used in the finally block, it will cause the return and raise statements in the try and except blocks to be invalidated. Look at the following program:

def test():
  try:
    # Because the finally block contains a return statement
    # So the following return statement loses its effect #
    return True
  finally:
    return False
print(test())

The above program defines a return False statement in the finally block, which causes the return true in the try block to lose its effect. Run the above program and the output will be:

False

Similarly, if a Python program executes a try block or an except block that contains a return or raise statement, the Python interpreter will look for the finally block first, and if it doesn't have a finally block, the program will immediately execute the return or raise statement; conversely, if it does find a finally block, the system will immediately begin executing the finally block, and only when the finally block is complete will it jump back to execute the return or raise statement. If there is no finally block, the program will immediately execute a return or raise statement; conversely, if a finally block is found, the program will immediately begin executing the finally block, and only when the finally block is complete will the program jump back to execute the return or raise statement in the try block or except block.

However, if you use a statement such as return or raise in the finally block that causes the method to abort, the finally block aborts the method, and the system will not go back and execute any of the code in the try or except blocks.

Try to avoid using statements like return or raise in the finally block that cause the method to abort, otherwise some very strange things may happen.

This is the whole content of this article.