Python进阶:异常处理与try/except案例
在Python编程中,异常处理是一个非常重要的概念。它允许我们编写代码来应对可能发生的错误情况,而不是让程序突然停止。
下面通过几个具体的try/except案例来理解异常处理:
- 简单除法:
```python
def divide(a, b):
try:
except ZeroDivisionError:result = a / b
return result
print("Cannot divide by zero.")
return None
Test the function
print(divide(10, 2))) # Output: 5.0
print(divide(10, 0))) # Output: Cannot divide by zero.
2. **文件操作**:
```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
# Test the function
print(read_file('testfile.txt'))) # Output: File testfile.txt not found.
通过以上的try/except案例,你已经对Python中的异常处理有了深入的理解。在实际编程中,灵活运用异常处理可以提高代码的健壮性。
还没有评论,来说两句吧...