Python进阶:异常处理与try/except案例

原创 Dear 丶 2025-03-18 00:27 16阅读 0赞

在Python编程中,异常处理是一个非常重要的概念。它允许我们编写代码来应对可能发生的错误情况,而不是让程序突然停止。

下面通过几个具体的try/except案例来理解异常处理:

  1. 简单除法
    ```python
    def divide(a, b):
    try:
    1. result = a / b
    2. return result
    except ZeroDivisionError:
    1. print("Cannot divide by zero.")
    2. return None

Test the function

print(divide(10, 2))) # Output: 5.0
print(divide(10, 0))) # Output: Cannot divide by zero.

  1. 2. **文件操作**:
  2. ```python
  3. def read_file(filename):
  4. try:
  5. with open(filename, 'r') as file:
  6. content = file.read()
  7. return content
  8. except FileNotFoundError:
  9. print(f"File {filename} not found.")
  10. return None
  11. # Test the function
  12. print(read_file('testfile.txt'))) # Output: File testfile.txt not found.

通过以上的try/except案例,你已经对Python中的异常处理有了深入的理解。在实际编程中,灵活运用异常处理可以提高代码的健壮性。

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

发表评论

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

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

相关阅读