异常处理
大约 2 分钟
# python的错误处理和java类似,采用 try...except...finally 等关键字
# 理解了java中的异常处理,就很容易上手python的异常处理代码
# 自定义异常
class FileReadError(FileNotFoundError):
def __init__(self, arg):
self.args = arg
print('这是用户自定义异常:', arg)
def func1():
print('func1...')
# try也可以嵌套,写到其他的try中
try:
print('外层try...')
file = open('test.txt', 'r')
try:
print('内层try...')
print(file.read())
r = 10 / 0
print('内层result:', r)
# 因为前面发生了异常,导致 file.close() 无法执行,资源无法释放
# 如果除了0除,还有其他异常,也无法捕获
raise RuntimeError('其他运行时异常')
return 1
# 可以带有多个异常
except (ZeroDivisionError, FileNotFoundError) as e:
print('内层except:', e)
return 2
# 可以有多个 except
except IndentationError as e:
print('内层except:', e)
return 3
else:
# 没有异常时才执行
print('内层执行其他语句...')
return 4
finally:
# 为了保险期间,在这里释放文件资源
print('内层finally...')
# 如果这里没有return,就会返回except中的值
return 5
# 使用自定义异常
except FileReadError('文件不存在') as e:
print('外层except:', e)
return 6
else:
print('外层执行其他语句...')
return 7
finally:
print('外层finally...')
return 8
print(func1())
# with可以简化 try...except...finally 结构
# 上下文管理器协议需要实现两个魔术方法:__enter__和__exit__
class User:
def __enter__(self):
print('__enter__')
print('在这里获取资源')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('在这里释放资源')
print('__exit__')
return True
def doSomething(self):
print('执行业务代码')
with User() as user:
user.doSomething()
# 可以通过contextlib简化上下文管理器
import contextlib
# 将某个函数变成上下文管理器
@contextlib.contextmanager
def file_read(path):
print('__enter__')
print('contextlib:在这里获取资源')
yield {}
print('contextlib:在这里释放资源')
print('__exit__')
with file_read('test.txt') as f:
print('执行业务代码')
感谢支持
更多内容,请移步《超级个体》。