示例:
如果f(x)提出一个值,然后我的功能必须返回字符串 “值”如果f(x)提出了typeError,则我的功能必须返回 字符串'type
,但我不知道该如何在Python中做到这一点。有人可以帮我吗? 我的代码是这样的:-
def reporter(f,x):
if f(x) is ValueError():
return 'Value'
elif f(x) is E2OddException():
return 'E2Odd'
elif f(x) is E2Exception("New Yorker"):
return 'E2'
elif f(x) is None:
return 'no problem'
else:
return 'generic'
您有python中的例外:-
def reporter(f,x):
try:
if f(x):
# f(x) is not None and not throw any exception. Your last case
return "Generic"
# f(x) is `None`
return "No Problem"
except ValueError:
return 'Value'
except TypeError:
return 'Type'
except E2OddException:
return 'E2Odd'
您将您的函数调用放在def reporter(f,x):
try:
if f(x) is None:
return 'no problem'
else:
return 'generic'
except ValueError:
return 'Value'
except E2OddException:
return 'E2Odd'
except E2Exception:
return 'E2'
构造中
功能本身不会返回异常,例外被捕获在外面。
DEF记者(F,X):
尝试: 如果f(x)无: 返回“没问题” 别的: 返回“通用” 除了Valueerror: 返回'值' 除了e2oddexception: 返回'e2odd' 除了E2Sception: 返回'e2'