Python中的异常处理:实例演示如何捕获和处理各种异常情况?
在Python中,我们可以使用try/except语句来捕获并处理异常。以下是一些实例:
- 普通错误:
```python
def divide_numbers(a, b):
try:
except ZeroDivisionError:result = a / b
return resultprint("Can't divide by zero!")
return None
print(divide_numbers(10, 2))) # Output: 5.0
print(divide_numbers(10, 0))) # Output: Can’t divide by zero!
2. 指定特定异常:
```python
def complex_operation():
try:
a = 1 / 0 # Simulating a ZeroDivisionError
except ZeroDivisionError:
print("Can't divide by zero!")
else:
print("Normal operation completed!")
complex_operation()
在这个例子中,我们模拟了一个除以零的错误。通过try/except语句,我们捕获了这个特定异常,并打印出了相应的消息。
还没有评论,来说两句吧...