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

相關文章
相關標籤/搜索