python try except finally 顺序

# encoding:utf-8
import traceback

def printException(e):
    print(e)
    traceback.print_exc()

def fun1():
    try:  
        a=1/0
    except Exception as e:  
        printException(e)
        print('except')
        # 执行到这里就开始执行 finally 下的内容,最后再到这里 return 1
        return 1
    finally:
        print('finally')
        # 若是这里有 return 就不会再走 except 下的 return 1 了,不然仍是会回去的
        return 2
        
re = fun1()
print('--------')
print(re)

输出:python

division by zero
Traceback (most recent call last):
  File "d:\code\python\test\tryCatch.py", line 10, in fun1
    a=1/0
ZeroDivisionError: division by zero
except
finally
--------
2code

相关文章
相关标签/搜索