Python中异常处理:try/except语句案例解析
在Python编程中,异常处理是一种策略,用于捕获和处理程序运行时可能出现的错误。这种机制主要通过try/except
语句来实现。
下面我们将通过几个实际案例来解析try/except
语句的使用方法。
- 基本用法:
```python
def divide(a, b):
try:
except ZeroDivisionError:result = a / b
return result
print("Can't divide by zero!")
return None
测试代码
print(divide(10, 2))) # 正确结果:5.0
print(divide(10, 0))) # 异常处理:Can’t divide by zero!
2. **使用except捕获特定错误**:
```python
def read_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"File {filename} not found!"))
return None
# 测试代码
print(read_file('test.txt')) or read_file('non_existent_file.py'))
- 使用finally段落确保任务完成:
```python
def download_file(url, filename):
try:
except Exception as e:response = requests.get(url)
with open(filename, 'wb') as file:
file.write(response.content)
print(f"File {filename} downloaded successfully!"))
finally:print(f"Error occurred during download: {str(e)}}")
print("Download process completed regardless of errors!")
测试代码
download_file(‘https://example.com/file.txt‘, ‘downloaded_file.txt’)
```
总结,Python中的异常处理通过try/except
语句来实现,它允许我们在遇到错误时采取适当的行动,比如捕获特定错误并进行处理,或者确保任务完成的任何操作。
还没有评论,来说两句吧...