Python中异常处理的最佳实践案例
在Python编程中,异常处理是确保程序不会因意外情况而崩溃的重要机制。以下是一些最佳实践案例:
- 使用try/except块:
```python
def divide(a, b):
try:
except ZeroDivisionError:result = a / b
return result
print("Can't divide by zero!")
divide(10, 2) # Normal division
divide(10, 0) # Exception handling for zero division
2. **捕获特定类型的异常**:
```python
def safe_division(a, b):
try:
return a / b
except TypeError: # Catch type errors not related to division
print("An error occurred while trying to divide numbers.")
except ZeroDivisionError: # Re-raise zero division error
raise
safe_division(10, '2')) # TypeError - Trying to divide a string by an integer.
- 使用finally块确保清理工作:
```python
def write_to_file(filename, content):
try:
except Exception as e:with open(filename, 'w') as file:
file.write(content)
print(f"Content written to {filename}."))
finally:print(f"Error occurred while writing to file: {e}")
# Always close the file, regardless of any errors
if 'file' in locals():
file.close()
write_to_file(‘test.txt’, ‘Hello, World!’)
```
以上就是Python中异常处理的最佳实践案例。
还没有评论,来说两句吧...