Python异常处理:理解try/except块应用案例
Python的异常处理是编程中必不可少的一部分。当代码执行过程中遇到错误,异常处理机制就会介入,帮助我们捕获、处理甚至忽视这些错误。
以下是一些使用try/except块的应用案例:
文件操作可能会出错,例如文件不存在:
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
网络请求可能会遇到网络问题:
```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}”)
3. 数据计算可能会遇到数据类型不匹配的问题:
```python
def add(a, b):
return a + b
try:
int_value = "42"
float_value = 0.123
result = add(int_value, float_value))
print("Sum: ", result)
except ValueError as e:
print(f"Value error occurred: {e}")
这些例子展示了如何使用try/except块来捕获和处理可能出现的异常。
还没有评论,来说两句吧...