Python中常见异常处理实例
在Python编程中,我们经常遇到各种异常。以下是一些常见的异常处理实例:
除数为零:
try:
div = 10 / 0
except ZeroDivisionError as e:
print("错误:", str(e)) # 输出: 错误: division by zero
文件不存在:
```python
file_path = “non_existent_file.txt”
try:
with open(file_path, ‘r’) as file:
content = file.read()
except FileNotFoundError as e:
print(“错误:”, str(e)) # 输出: 错误: [Errno 2] No such file or directory: ‘non_existent_file.txt’
3. **输入不是整数**:
```python
try:
num = input("请输入一个整数: "))
int_num = int(num)
except ValueError as e:
print("错误:", str(e)) # 输出: 错误: cannot convert 'str' to 'int'
以上就是一些常见的异常处理实例,通过这些例子你可以更好地理解Python中的异常处理。
还没有评论,来说两句吧...