我在代码中添加了错误处理,但我认为它完全破坏了它的外观。所以我想创建一个函数来完成所有错误处理,但我在网上找不到任何示例,所以我尝试自己想出一些东西..
def checkerr(datatype,obj):
try:
var=datatype(obj)
return(var)
except ValueError as error:
print(error,'you did not type in an integer')
except IOError as error:
print(error,'file could not be found')
no=input('type in an integer: ')
realno=checkerr(int,no)
file=input('type in a filenane: ')
realfile=checkerr(open,file)
应该怎样做?
最佳答案
你的路走得很好。在函数中定义这段代码可以让您 avoid repetitions .
但是最好重新询问用户直到输入有效,这样您就可以依赖该函数始终返回一个好的值。
在第一次尝试失败后,您的函数将返回 None
。那么代码又会变得复杂。
我的建议:
def ask(prompt, datatype):
while True:
obj = input(prompt)
try:
var = datatype(obj)
return(var)
except (ValueError, IOError) as error:
print(error)
示例:
>>> i = ask('type in an integer: ', int); print('you entered: %d' % i)
type in an integer: two
invalid literal for int() with base 10: 'two'
type in an integer: 2
you entered: 2
关于python - 制作一个处理所有错误的函数正常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50141558/