Python异常处理:try/except语句应用实例
在Python编程中,异常处理是一个非常重要的概念。它允许我们在代码遇到错误时,提供一种优雅的控制方式,而不是让程序直接崩溃。下面是一些关于try/except语句的应用实例:
- 文件操作可能出错,如文件不存在等:
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")
数据验证也可能出现错误:
```python
def validate_age(age):
if age < 0 or age > 150: # Invalid age rangeraise ValueError("Age out of range.")
return age
try:
age = int(input(“Enter your age: “)))
validated_age = validate_age(age)
print(f”Validated age: {validated_age}”)
except ValueError as ve:
print(ve)
3. 网络请求也可能失败,可以使用try/except处理:
```python
import requests
def fetch_data(url):
try:
response = requests.get(url, timeout=5) # 设置超时时间
if response.status_code == 200: # 如果状态码是200(成功),返回数据
data = response.text
return data
else:
print(f"Failed to fetch data. Status code: {response.status_code}.")
except requests.exceptions.RequestException as e:
print(e)
url = "https://api.example.com/data"
data = fetch_data(url)
if data is not None:
process_data(data)
在这个例子中,我们展示了如何使用try/except语句来处理可能出现的异常情况。
还没有评论,来说两句吧...