默认异常处理器,即由python自动搜索匹配对应的异常信息
# python命令行,默认是3.6,以下没有特殊说明全部是基于这个版本
>>> str="keithl"
>>> str[10]
Traceback (most recent call last):
File "" , line 1, in <module>
IndexError: string index out of range
捕获异常信息
# exception.py
def catch_index():
str="keithl"
try:
print(str[10])
# print(str[2])
except IndexError as e:
print(e)
else:
print("try正常执行,没有异常发生...")
if __name__ == '__main__':
catch_index()
抛出异常,使用raise
# exception.py
def raise_index():
str = "keithl"
try:
print(str[10])
except IndexError as e:
raise e
if __name__ == '__main__':
raise_index()
自定义异常
# exception.py
class MyException(Exception):
def __str__(self):
return "my exception object"
def define_exception():
try:
raise MyException
except MyException as e:
print("get my exception error[%s]" % str(e))
if __name__ == '__main__':
define_exception()
使用finally终止try语句
# exception.py
def raise_index_finally():
str = "keithl"
try:
print(str[10])
except IndexError:
print("except index error")
finally:
print("try statement to close resource ...")
if __name__ == '__main__':
raise_index_finally()
try/except/else语句
try:
print("程序业务逻辑.")
except name1:
print("捕获异常name1..")
except (name2, name3):
print("捕获异常name2 或 name3..")
except name4 as var:
print("捕获异常name4,并传递其引用变量到语句块中..")
except: # 5
print("捕获所有异常(上述的name1,name2,name3,name4除外..)")
else:
print("没有异常,try语句正常执行..")
try/except/else工作原理
捕获任意或所有异常
except:
,即后面没有携带任何异常类,将会捕获先前没有定义的异常类except (e1,e2,..)
,即只要业务代码中抛出的异常是在定义的一系列异常列表中(e1,e2,…),那么就会在except语句中被捕获处理except:
与except Exception:
except:
是捕获所有的异常,但存在不足,一是捕获和业务代码无关的系统错误,二是会拦截其他程序的异常处理except Exception:
:py3.x建议使用这个Exception类,同时可以避免上述问题,Exception会忽略与系统操作相关的异常,如系统退出py时报出的异常# exception.py
# `except:`执行遇到系统退出的时候会捕获异常
def test_exception():
try:
for i in range(10):
print(i)
if i == 5:
sys.exit(-1)
except:
print("直接使用空的异常来捕获")
if __name__ == '__main__':
test_exception()
>>> python exception.py
# `except Exception:`在系统退出的时候没有捕获异常
def test_exception():
try:
for i in range(10):
print(i)
if i == 5:
sys.exit(-1)
except Exception:
print("直接使用空的异常来捕获")
if __name__ == '__main__':
test_exception()
>>> python exception.py
except Exception as e
以及except Exception,e
,py3.x仅支持except Exception as e
try/finally语句
try:
print("执行业务代码语句块...")
finally:
print("关闭处理业务的资源...")
try/finally工作原理
示例
# exception.py
def raise_exception():
raise MyException()
def test_try_finally():
try:
raise_exception()
finally:
print("execute test_try_finally statement ...")
if __name__ == '__main__':
test_try_finally()
>>> python exception.py
try/except/finally语句
try:
print("处理核心业务逻辑")
except Exception as e1:
print("捕获异常信息e1")
except Exception as e2:
print("捕获异常信息e2")
else:
print("try的业务语句没有异常,正常执行完毕后将执行else语句")
finally:
print("关闭消耗CPU的资源")
raise语句
raise:将一个异常类class信息抛出并往顶层程序传播
raise newException from otherException
class MyException(Exception):pass
try:
raise IndexError
except Exception as e:
raise MyException from e
assert语句
assert test,data # data是可选的
if __debug__:
if not test:
raise AssertionError(data)
with/as上下文管理器
with expression [as variable]
with-block
# 表达式expression返回的是一个实现上下文管理器协议的对象
# 打开文件filepath并且自动读取
with open("filepath") as file_object:
for line in file_object:
print(line)
# 在一个线程中对语句块进行锁操作
lock = threading.Lock() # 导入threading模块
with lock: # 在业务代码执行之前自动获取锁,在执行完成之后自动释放锁,除非有异常抛出
# 执行相关的业务代码
pass
import decimal
with decimal.localcontext() as ctx:
ctx.prec = 2 # 保留小数点后两位
x = decimal.Decimal('5.00') / decimal.Decimal('3.00')
__enter__
和__exit__
方法__enter__
方法__exit__
的方法,同时携带type,value,traceback三个参数(通过sys.exc_info获取到)__exit__
的方法# exception.py
class WithContextObject:
def message(self,args):
print(args)
def __enter__(self):
print("execute enter method ..")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
print("execute normally...")
else:
print("raise exception ...")
return False
def test_with():
with WithContextObject() as context:
context.message("take message")
if __name__ == '__main__':
test_with()
>>> python exception.py
# 基本语法
with open(file_path1) as reader,with open(file_path2) as writer:
for line in reader:
writer.write(line)
# 等价于
with open(file_path1) as reader:
with open(file_path2) as writer:
for line in reader:
writer.write(line)
如有收获,欢迎关注个人公众号: