python触发异常有两个函数:assert、raise,但他们有本地的区别:
- assert 表达式, 自定义报错的信息(可选):根据表达式是否报错触发异常
- raise [指定异常类型 [描述信息]]:直接触发(抛出)异常
- assert 多表达式:
assert 表达式1 [, 参数] 表达式2 [, 参数]
表达式都为真才不会触发异常 查看异常类型:
import exceptions dir(exceptions)
try:
assert 1+2<4,"计算错误"
assert 1+2>5, "比较错误"
except AssertionError as e:
print(e)
# 输出
# 比较错误
```python a = 1 assert a < 0, ‘出错了,a大于0 啊’ print(‘这里不会输出’)
输出
Traceback (most recent call last):
File “main.py”, line 3, in
assert a < 0, ‘出错了,a大于0 啊’
AssertionError: 出错了,a大于0 啊
```python
a = 1
b = -1
assert a > 0, b < 0
print('正常输出,表达式返回真了') # 输出:正常输出,表达式返回真了