【发布时间】:2016-08-21 13:46:21
【问题描述】:
我想根据TypeError 的具体原因返回一组自定义消息。
def f(x, y):
value = x + y
return "Success! ({})".format(value)
def safe(function, *args):
try:
result = function(*args)
except TypeError:
if "not_enough_args": # What actual condition can go here?
return "Not enough arguments."
elif "too_many_args": # What actual condition can go here?
return "Too many arguments."
else:
return "A TypeError occurred!"
else:
return result
safe(f, 2) # "Not enough arguments."
safe(f, 2, 2) # "Success!"
safe(f, 2, 2, 2) # "Too many arguments."
safe(f, '2', 2) # "A TypeError occurred!"
最好使用实际的TypeError 对象。
【问题讨论】:
-
只适用于有两个参数的函数还是任何函数?
-
@MoonCheesez 任何功能。
标签: python python-3.x exception response