面对异常,Python中捕获和处理错误的实例
在Python编程中,处理异常是非常关键的一部分。这里,我将通过几个实际的例子来展示如何使用try/except块捕获和处理错误。
- 除数为零:
# 示例1:尝试除以0
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
- 文件不存在:
# 示例2:尝试打开一个不存在的文件
file_path = "non_existent_file.txt"
try:
with open(file_path, 'r') as file:
content = file.read()
except FileNotFoundError:
print("Error: The specified file does not exist.")
- 网络请求失败:
import requests
# 示例3:尝试获取一个不存在的URL的内容
url = "https://nonexistentwebsite.com"
try:
response = requests.get(url)
if response.status_code == 404:
print("Error: The specified URL does not exist.")
else:
content = response.text
print(content)
except Exception as e:
print(f"Error: {str(e)})}")
这些例子展示了如何在Python中使用try/except块来捕获和处理各种类型的错误。
还没有评论,来说两句吧...