Python异常处理:理解try/except块应用案例

原创 痛定思痛。 2025-01-24 03:27 33阅读 0赞

Python的异常处理是编程中必不可少的一部分。当代码执行过程中遇到错误,异常处理机制就会介入,帮助我们捕获、处理甚至忽视这些错误。

以下是一些使用try/except块的应用案例:

  1. 文件操作可能会出错,例如文件不存在:

    1. try:
    2. with open('non_existent_file.txt', 'r') as file:
    3. content = file.read()
    4. except FileNotFoundError:
    5. print("File not found.")
  2. 网络请求可能会遇到网络问题:
    ```python
    import requests

try:
response = requests.get(‘http://example.com‘)
status_code = response.status_code
if status_code == 200:
content = response.text
print(“Success! Content:”, content)
else:
print(“Failed! Status Code:”, status_code)
except requests.exceptions.RequestException as e:
print(f”An error occurred: {e}”)

  1. 3. 数据计算可能会遇到数据类型不匹配的问题:
  2. ```python
  3. def add(a, b):
  4. return a + b
  5. try:
  6. int_value = "42"
  7. float_value = 0.123
  8. result = add(int_value, float_value))
  9. print("Sum: ", result)
  10. except ValueError as e:
  11. print(f"Value error occurred: {e}")

这些例子展示了如何使用try/except块来捕获和处理可能出现的异常。

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

发表评论

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

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

相关阅读