一般情况下, python 无法捕获被调用函数的参数异常, 但是用装饰器可以实现此功能.
先定义一个 check
装饰器:
import traceback
import sys
def check(method):
'''
check argument
'''
def wrapper(*args, **kw):
try:
return method(*args, **kw)
except TypeError as e:
print("I catch you!")
stack = traceback.format_list(traceback.extract_stack())
for line in stack:
print('>> '+line.strip())
print(sys.exc_info())
return wrapper
再把要被调用的函数加上装饰器:
@check
def hello(msg):
print(msg)
hello()
输出如下, 可以看到, check
装饰器已经捕获到 TypeError
异常了
网友评论