[Python] Exception Handling ① ( Exception Concept | Exception Handling | Exception Capture )





1. Introduction to Python exceptions




1. Abnormal concept


A Python exception is an indication of an error or problem that occurs during the running of a program;

An exception may interrupt the normal execution flow of the program and raise an exception object;

At this point, the exception object needs to be captured and processed to prevent the program from crashing or causing more serious errors;


2. Python exception example


In the previous blog, the file operation was introduced. If a non-existing file is opened in read-only mode, an exception will occur;

An exception code occurred:

"""
文件操作 代码示例
"""
import time

with open("file3.txt", "r", encoding="UTF-8") as file:
    print("使用 write / flush 函数向文件中写出数据(以追加模式打开文件): ")

    # 写出数据
    file.write("Tom and Jerry")

    # 刷新数据
    file.flush()

    # 关闭文件
    file.close()

Abnormal :

/Users/zyq/PycharmProjects/Hello/venv/bin/python /Users/zyq/PycharmProjects/Hello/main.py 
Traceback (most recent call last):
  File "/Users/zyq/PycharmProjects/Hello/main.py", line 6, in <module>
    with open("file3.txt", "r", encoding="UTF-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'file3.txt'

Process finished with exit code 1

insert image description here





2. Python exception handling



There are two situations where the program is abnormal:

  • The entire application stops running because of this exception;
  • The exception is caught and processed, and the application runs normally;

1. Introduction to exception handling


The program cannot run due to an abnormality. In this case, it does not require the program to run perfectly without abnormality, but to handle possible abnormalities within the scope of its ability;

Exception handling is to prepare in advance for possible exceptions in the code block where exceptions may occur, catch exceptions when exceptions occur, and then perform different processing for exception types;

Exception catch syntax:

try:
	可能出现异常的代码块
except:
	出现异常后执行的代码块

2. Code example - abnormal code


implement

"""
文件操作 代码示例
"""

open("file3.txt", "r", encoding="UTF-8")

code, the following exception information will be reported:

Traceback (most recent call last):
  File "/Users/zyq/PycharmProjects/Hello/main.py", line 6, in <module>
    open("file3.txt", "r", encoding="UTF-8")
FileNotFoundError: [Errno 2] No such file or directory: 'file3.txt'

3. Code example - an exception occurs and is captured and processed


Code example:

"""
文件操作 代码示例
"""

try:
    open("file3.txt", "r", encoding="UTF-8")
except:
    print("出现异常, 进行异常处理")
    open("file3.txt", "w", encoding="UTF-8")

Results of the :

/Users/zyq/PycharmProjects/Hello/venv/bin/python /Users/zyq/PycharmProjects/Hello/main.py 
出现异常, 进行异常处理

Process finished with exit code 0

insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/131353800