用IDLE Shell软件编写程序实现“用异常的观点来实现加减乘除的四则运算(分别用3种异常处理方式来实现)”
时间: 2024-11-03 19:15:23 浏览: 14
在Python中,我们可以使用异常处理机制来优雅地处理除数为零或其他错误的四则运算情况。这里我们将展示三种常见的异常处理方式:`try-except`、`raise` 和 `assert`。
1. **使用 try-except**:
```python
def arithmetic_operation(num1, num2, operation):
try:
if operation == 'add':
return num1 + num2
elif operation == 'subtract':
return num1 - num2
elif operation == 'multiply':
return num1 * num2
elif operation == 'divide':
result = num1 / num2
if num2 == 0:
raise ZeroDivisionError("除数不能为零")
else:
return result
except ZeroDivisionError as e:
print(f"发生错误:{str(e)}")
return None
num1 = 10
num2 = 0
operation = 'divide'
print(arithmetic_operation(num1, num2, operation))
```
2. **使用 raise** 直接抛出异常:
```python
def safe_division(num1, num2, operation):
if operation == 'divide':
if num2 == 0:
raise ValueError("除数不能为零")
return num1 / num2
else:
return num1 * num2 or num1 + num2 or num1 - num2
try:
result = safe_division(10, 0, 'divide')
except ValueError as e:
print(f"发生错误:{str(e)}")
```
3. **使用 assert** 检查条件并抛出异常:
```python
def arithmetic_operation_assert(num1, num2, operation):
if operation == 'divide':
assert num2 != 0, "除数不能为零"
return num1 / num2
else:
return num1 * num2 or num1 + num2 or num1 - num2
result = arithmetic_operation_assert(10, 0, 'divide')
if result is None:
print("发生错误:除数不能为零")
else:
print(result)
```
每种方法都有其适用场景,可以根据实际需求选择最合适的异常处理策略。
阅读全文