try的工作原理是,开始一个try语句后,Python就在当前程序的上下文中做标记,当出现异常时就可以回到做标记的地方。首先执行try子句,接下来发生什么依赖于执行时是否出现异常。
如果try后的语句执行时发生异常,程序就跳回try并执行except子句。异常处理完毕后,控制流就可以通过整个try语句了(除非在处理异常时又引发新异常)。
class TestError(Exception):
def __init__(self, errcode, errmsg):
self.errcode = errcode
self.errmsg = errmsg
def __str__(self):
return f'errcode:{self.errcode},errmsg:{self.errmsg}'
def ex(execption_type):
try:
if execption_type == 'raise':
raise Exception('raise threw Exception')
elif execption_type == 'assert':
assert 0 > 0, 'assert threw Exception'
elif execption_type == 'test':
raise TestError(0x0012, 'error message undefinde')
except AssertionError as e:
print(e)
except TestError as e:
print(e)
except Exception as e:
print(e) ##e.str()
else:
print('if no errors ,i do')
finally:
print('i always do')
ex('raise')
raise threw Exception
i always do
ex('assert')
assert threw Exception
i always do
ex('test')
#errcode:18,errmsg:error message undefinde
#i always do
ex('ok')
if no errors ,i do
i always do
评论