try
and except
are keywords used in Python to handle exceptions. Exceptions are errors or unusual conditions that may occur during program execution. By using try
and except
, you can write code to catch and handle these exceptions to avoid program crashes.
try:
# 你的代码,可能会引发异常
result = 10 / 0 # 这里故意引发一个除零异常
except ZeroDivisionError:
# 处理特定类型的异常
print("除零异常发生")
except Exception as e:
# 处理其他类型的异常
print(f"发生了异常:{e}")
else:
# 如果没有异常发生,执行这里的代码
print("没有异常发生")
finally:
# 无论是否发生异常,都会执行这里的代码
print("无论如何都会执行的代码")
Uses ZeroDivisionError
to catch a specific exception (divide-by-zero exception). If this exception occurs, the program executes the code in the first except
block. If another type of exception occurs, the program executes the code in the second except
block. If no exception occurs, the program executes the code in the else
block. Regardless of whether an exception occurs, the code in the finally
block will be executed.
Note: Python has many built-in exception types.
ZeroDivisionError
:Division by zero error.ValueError
: Value error, usually occurs when trying to pass an invalid value to a function or operation.TypeError
: Type error, usually occurs when operating on incompatible data types.FileNotFoundError
: File not found error, usually occurs when trying to open a file that does not exist.MemoryError
: Memory error, usually indicating that the program has exhausted available memory resources.