Python中异常处理:实战案例分析
在Python编程中,异常处理是一种机制,用于在程序执行过程中遇到错误时进行控制。以下是一些实际的案例分析:
除以零:
try:
x = 10 / 5
print(x) # 正确输出:2
except ZeroDivisionError:
print("Can't divide by zero!") # 当遇到除以零时,输出指定信息。
文件操作:
try:
with open('test.txt', 'r') as f:
content = f.read()
print(content) # 正确输出:Hello, world!
except FileNotFoundError:
print("File not found! Check the file name and path.")
网络请求:
import requests
try:
response = requests.get('https://example.com')
if response.status_code == 200: # 状态码为200表示成功
content = response.text
print(content)
else:
print(f"Failed to fetch data. Status code: {response.status_code}.")
except requests.RequestException as e:
print(f"An error occurred during network request: {e}")
通过以上的案例,你可以看到在Python中如何使用异常处理来优雅地处理可能出现的错误。
还没有评论,来说两句吧...