Python中异常处理:常见错误捕获示例

原创 Myth丶恋晨 2025-02-20 06:33 34阅读 0赞

在Python编程中,异常处理是一种机制,用于在程序执行过程中遇到错误时进行适当的处理。以下是一些常见的错误捕获示例:

  1. 使用try/except块捕捉特定错误
    ```python
    def divide(a, b):
    try:
    1. return a / b
    except ZeroDivisionError:
    1. print("Can't divide by zero!")
    2. return None

result = divide(10, 2)
print(result) # Output: 5.0

  1. 2. **使用except所有错误**:
  2. ```python
  3. def perform_operation(a, b):
  4. try:
  5. result = a + b
  6. print("Operation performed successfully.")
  7. return result
  8. except Exception as e:
  9. print("An error occurred:", str(e)))
  10. return None
  11. result = perform_operation(5, "2")
  12. print(result) # Output: An error occurred: can't convert 'str' to 'int'
  1. 使用finally块确保某项操作始终执行
    ```python
    def write_to_file(file_name, content):
    try:
    1. with open(file_name, 'w') as file:
    2. file.write(content)
    3. print(f"Content written to '{file_name}' successfully.")
    4. return True
    except Exception as e:
    1. print("An error occurred:", str(e)))
    2. finally:
    3. print("File operation cleanup performed.")
    4. return False

result = write_to_file(‘test.txt’, “Hello, World!”)
print(result) # Output: Content written to ‘test.txt’ successfully.
```
通过这些示例,你可以理解如何在Python中使用异常处理来捕获和处理错误。

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

发表评论

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

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

相关阅读