1. 程式人生 > >python try except finally 順序

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)

輸出:

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
final