如何在python中的if语句中测试异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14516873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I test for exceptions in if-statements in python?
提问by user2010023
i want to write a function to report the different results from another function there are some exceptions among these results but I cannot convert them into if statement
我想编写一个函数来报告来自另一个函数的不同结果,这些结果中有一些例外,但我无法将它们转换为 if 语句
example :
例子 :
if f(x) raise a ValueError, then my function has to return a string 'Value' if f(x) raise a TypeError, then my function has to return a string 'Type
如果 f(x) 引发一个 ValueError,那么我的函数必须返回一个字符串 'Value' 如果 f(x) 引发一个 TypeError,那么我的函数必须返回一个字符串 'Type'
But I don't know how to do this in Python. Can someone help me out.
但我不知道如何在 Python 中做到这一点。有人可以帮我吗。
My Code is like this: -
我的代码是这样的:-
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'
采纳答案by Rohit Jain
You have try-exceptto handle exceptions in Python: -
您必须try-except在 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'
回答by Alex
You put your function call in a try-exceptconstruct like
你把你的函数调用放在一个try-except像
try:
f(x)
except ValueError as e:
return "Value"
except E20ddException as e:
return "E20dd"
The function itself does not return the exception, the exception is caught outside.
函数本身不返回异常,异常被外部捕获。
回答by inspectorG4dget
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'

