Python异常处理:常见的捕获和处理方式

原创 小咪咪 2025-02-07 01:33 46阅读 0赞

在Python中,异常处理是一种机制,允许我们在程序运行时遇到错误时进行适当的处理。以下是几种常见的捕获和处理方式:

  1. try/except

    1. try:
    2. # 这里是可能会引发错误的代码
    3. result = 10 / 0 # 这会引发除以零的错误
    4. print(result)
    5. except ZeroDivisionError: # 捕获特定类型的错误
    6. print("Error: Division by zero is not allowed.")
  2. finally

    1. try:
    2. result = 10 / 0 # 这会引发错误
    3. print(result)
    4. except ZeroDivisionError:
    5. pass # 不处理,直接跳过
    6. finally:
    7. print("This is always executed, regardless of errors or exceptions.")
  3. assert

    1. def check_positive(x):
    2. assert x > 0, f"Value {x} should be positive."
    3. check_positive(-1) # 这会引发错误,因为-1不是正数

通过以上这些方式,我们可以在遇到错误时进行适当的处理,保证程序的稳定运行。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,46人围观)

还没有评论,来说两句吧...

相关阅读