python - 制作一个处理所有错误的函数正常吗?

标签 python python-3.x function error-handling

我在代码中添加了错误处理,但我认为它完全破坏了它的外观。所以我想创建一个函数来完成所有错误处理,但我在网上找不到任何示例,所以我尝试自己想出一些东西..

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/

相关文章:

python - 类对象赋值时不规则

json - 调用函数将 Json 从 View Controller 解析到其他 View

Python:为 Windows 7 安装 Tesseract

python - 在 Markdown 中运行 Python 代码

Python正则表达式匹配整数但不匹配 float

python - 与图像不同的是与keras的conv2D进行卷积

python - 值错误 : Cannot serialize function: lambda while using makemigrations

python - 解压字典并将其作为关键字参数传递给函数

python - 找到未知范围内的数字的最快方法?

c - 原始 C 中不完整的 beta 函数