在 Python 中,异常处理是一种处理程序运行时错误的机制。异常是在程序执行过程中发生的错误,它可以干扰正常的程序流程。为了提高程序的稳定性和可维护性,Python 提供了一套异常处理机制。以下是一些基础的异常处理知识:

1. try、except 块

使用 try、except 块来捕获和处理异常。try 块包含可能引发异常的代码,而 except 块包含处理异常的代码。
try:
    # 可能引发异常的代码
    result = 10 / 0
except ZeroDivisionError:
    # 处理特定异常
    print("Division by zero is not allowed.")
except Exception as e:
    # 处理其他异常
    print(f"An error occurred: {e}")

2. 多个 except 块

可以使用多个 except 块来处理不同类型的异常。
try:
    # 可能引发异常的代码
    value = int("abc")
except ValueError:
    # 处理值错误异常
    print("Invalid conversion to int.")
except ZeroDivisionError:
    # 处理除零异常
    print("Division by zero is not allowed.")
except Exception as e:
    # 处理其他异常
    print(f"An error occurred: {e}")

3. else 块

可以使用 else 块在没有异常发生时执行特定的代码。
try:
    # 可能引发异常的代码
    result = 10 / 2
except ZeroDivisionError:
    print("Division by zero is not allowed.")
else:
    # 在没有异常发生时执行的代码
    print(f"Result: {result}")

4. finally 块

可以使用 finally 块来执行无论是否发生异常都需要执行的代码。
try:
    # 可能引发异常的代码
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed.")
finally:
    # 无论是否发生异常,都会执行的代码
    print("This block always executes.")

5. 抛出异常

使用 raise 语句来手动引发异常。
try:
    age = int(input("Enter your age: "))
    if age < 0:
        raise ValueError("Age cannot be negative.")
except ValueError as e:
    print(f"Invalid input: {e}")

这些是 Python 异常处理的基础知识。通过合理使用异常处理机制,可以提高程序的健壮性,使其能够更好地处理各种异常情况。


转载请注明出处:http://www.zyzy.cn/article/detail/13332/Python 基础