异常(Exception)
异常处理
异常的传播
- python异常会自动向上传播,不用像其它语言一样手动抛出
- 异常被处理后不会再向上传播
- 如果异常一直没有被处理,就一直向上传播,到最后程序终止并输出异常信息
- 在程序运行过程中,所有异常信息都会保存在一个异常对象中,向上传播时,实际上就是把异常对象向上传递或叫返回,最后解析出异常对象信息并输出
抛出异常
- 语法:raise 异常类(‘异常描述’)
- 在开发过程中,有时我们需要抛出一个异常以来提醒别人
- 比如说:我们在运算函数中,不希望入参为负数,可以这样写
def add(a,b):
if a < 0 or b < 0:
raise Exception('参数不可以为负数')
add(1,-1)
# 执行结果打印
# Traceback (most recent call last):
# File "testb.py", line 7, in <module>
# add(1,-1)
# File "testb.py", line 4, in add
# raise Exception('参数不可以为负数')
# Exception: 参数不可以为负数
# ***Repl Closed***
自定义异常
class MyError(Exception):
pass
def add(a,b):
if a < 0 or b < 0:
raise MyError('参数不可以为负数')
add(1,-1)
# 执行结果打印
# Traceback (most recent call last):
# File "testb.py", line 10, in <module>
# add(1,-1)
# File "testb.py", line 8, in add
# raise MyError('参数不可以为负数')
# __main__.MyError: 参数不可以为负数
# ***Repl Closed***