[Python] Exception Handling② ( Introduction to Exception Types | Catch and Handle Specified Exceptions | Catch Multiple Types of Exceptions )





1. Python captures the specified type of exception




1. Introduction to exception types


Exceptions in Python are represented by the exception class Exception Class, and each exception class represents a specific error type;

Common exception classes:

  • FileNotFoundError : Indicates an error in opening a file that does not exist;
  • ZeroDivisionError : Indicates a division by zero error;
  • ValueError : Indicates an invalid value;
  • KeyError : Indicates that the specified key does not exist in the dictionary;
  • IndexError : Indicates that the specified index does not exist in the list or tuple;
  • IOError : Indicates an I/O error, such as an inability to read or write a file;

When an exception occurs, the program will stop executing the current statement and jump to the exception handler Exception Handler, which is responsible for handling the exception and preventing the program from crashing;

In Python, exceptions can be caught and handled using the try-except statement;


2. Catch and handle specified exceptions


In Python, exceptions of specified types can be caught, the syntax is as follows:

try:
	可能出现异常的代码块
except 异常类型 as 异常别名:
	出现异常后执行的代码块
	可使用异常别名获取异常对象
	

3. Code example - capture and handle specified exceptions


Code example:

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

try:
    open("file3.txt", "r", encoding="UTF-8")
except FileNotFoundError as e:
    print(f"出现异常, 进行异常处理, 异常内容 : {
      
      e}")
    open("file3.txt", "w", encoding="UTF-8")

Results of the :

/Users/zyq/PycharmProjects/Hello/venv/bin/python /Users/zyq/PycharmProjects/Hello/main.py 
出现异常, 进行异常处理, 异常内容 : [Errno 2] No such file or directory: 'file3.txt'

Process finished with exit code 0

insert image description here


4. Code example - exception capture failure case


If the correct exception is not caught when the exception is caught, the exception will still explode and the program will be terminated;

In the following code, what is captured is FileNotFoundError, if other types of exceptions occur, such as ZeroDivisionError, it will directly cause the program to stop running;

The following code executes num = 1 / 0the code , and a ZeroDivisionError exception will be reported;


Code example:

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

try:
    num = 1 / 0
    open("file3.txt", "r", encoding="UTF-8")
except FileNotFoundError as e:
    print(f"出现异常, 进行异常处理, 异常内容 : {
      
      e}")
    open("file3.txt", "w", encoding="UTF-8")

Results of the :

/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>
    num = 1 / 0
ZeroDivisionError: division by zero

Process finished with exit code 1





2. Python captures multiple types of exceptions




1. Catch multiple exception syntax


Catch multiple exception syntax:

try:
	可能出现异常的代码块
except (异常类型1, 异常类型2, 异常类型3, ...) as 异常别名:
	出现异常后执行的代码块
	可使用异常别名获取异常对象

2. Code example - catch multiple exceptions


In the following code, two kinds of exceptions, FileNotFoundError and ZeroDivisionError, may appear, and these two kinds of exceptions are caught at the same time when the exception is caught;

During execution, if one of these two exceptions occurs, the exception will be caught and processed;


Code example:

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

try:
    num = 1 / 0
    open("file3.txt", "r", encoding="UTF-8")
except (FileNotFoundError, ZeroDivisionError) as e:
    print(f"出现异常, 进行异常处理, 异常内容 : {
      
      e}")

Results of the :

/Users/zyq/PycharmProjects/Hello/venv/bin/python /Users/zyq/PycharmProjects/Hello/main.py 
出现异常, 进行异常处理, 异常内容 : division by zero

Process finished with exit code 0

Guess you like

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