Skip to main content
 首页 » 编程设计

python之创建一个处理所有错误的函数是否正常

2024年09月07日8TianFang

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

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