Python异常处理:try/except语句的应用实例
在Python编程中,try/except
语句用于处理可能出现的异常情况。下面是一些具体的应用实例:
- 文件操作可能会出错,比如文件不存在:
```python
file_path = “nonexistent_file.txt”
try:
with open(file_path, ‘r’) as file:
content = file.read()
except FileNotFoundError:
print(f”File {file_path} not found.”)
2. 进行网络请求时可能会遇到HTTP错误,如404(未找到):
```python
def get_data(url):
try:
response = requests.get(url)
if response.status_code == 404:
return "Page not found."
else:
return response.text
except requests.exceptions.RequestException as e:
print(f"Error occurred: {e}")
- 在计算过程中,可能会出现除以零的错误,需要捕获并处理:
```python
def divide_by_zero():
try:
except ZeroDivisionError:result = 10 / 0
print("Result:", result)
print("Error: Division by zero is not allowed.")
divide_by_zero()
```
以上就是Python中try/except
语句的常见应用实例。
还没有评论,来说两句吧...