赞
踩
msg = "" def test(): try: raise Exception("文件解压失败") except NameError: pass try: print("test") except Exception: pass def main(): try: test() print("main") except Exception: print("not now") main()
函数内部未捕获异常异常被外层异常捕获,且函数内部代码不继续执行。
PS F:\workspace\Template> python .\try.py
not now
函数内部异常被捕获则不会再被捕获
def test(): try: raise Exception("文件解压失败") except Exception: pass try: print("test") except Exception: pass def main(): try: test() print("main") except Exception: print("not now") main()
代码异常被捕获且继续执行
PS F:\workspace\Template> python .\try.py
test
main
异常被捕获则不影响代码继续执行,且外层不捕获异常,但是try内部代码触发异常以后不再继续执行
def test():
try:
try:
print("in1")
raise Exception("文件解压失败")
except Exception:
pass
print("in2")
except Exception:
print("out")
test()
PS F:\workspace\Template> python .\try.py
in1
in2
def test():
try:
try:
print("in1")
raise NameError("文件解压失败")
print("try in2")
except Exception:
raise NameError()
pass
print("in2")
except Exception:
print("out")
test()
PS F:\workspace\Template> python .\try.py
in1
out
本质上触发异常就不继续运行 ,所以尽量将try写的细点。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。