Article directory
1. Python catches all types of exceptions by default
1. By default, all types of exceptions are caught - the exception type cannot be obtained
Using the try-except statement, without specifying the exception type, all types of exceptions can be caught by default;
The syntax is as follows −
try:
可能出现异常的代码块
except:
出现异常后执行的代码块
In this case, the exception can be caught, but the exception type cannot be obtained;
2. Code example - catch all types of exceptions by default
Code example:
"""
异常处理操作 代码示例
"""
try:
num = 1 / 0
open("file3.txt", "r", encoding="UTF-8")
except:
print(f"出现异常, 进行异常处理")
Results of the :
/Users/zyq/PycharmProjects/Hello/venv/bin/python /Users/zyq/PycharmProjects/Hello/main.py
出现异常, 进行异常处理, 异常内容
Process finished with exit code 0
2. Python catches all types of exceptions - catches Exception
1. Catch Exception type exception - can get exception type
In Python, all types of exceptions can be caught using the try-except statement;
When using the try-except statement, you can put all the code that may throw an exception in the try block, and then use the except block to catch all types of exceptions;
In the except block, you can specify the exception type to be caught, or use Exception to catch all types of exceptions;
Use the try-except statement to catch exceptions of the Exception type, and you can get all exception objects;
The syntax is as follows −
try:
可能出现异常的代码块
except Exception as e:
出现异常后执行的代码块
In this case, the exception can be caught, but the exception type cannot be obtained;
2. Code example - catch Exception exception
Code example:
"""
异常处理操作 代码示例
"""
try:
num = 1 / 0
open("file3.txt", "r", encoding="UTF-8")
except Exception 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