如何在python中处理和设置错误,返回和返回值?

时间:2016-03-10 14:50:45

标签: python python-2.7 error-handling return return-value

我是编程新手,有人可以告诉我有什么区别以及如何处理python中的错误?

def compare_files(file1, file2):
    status = 0
    try:
        with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
            if f_file1.read() == f_file2.read():
                print 'SUCCESS \n'
            else:
                print 'FAILURE \n'
                status = 1
    except IOError:
        print "[Error]File is NOT compared"
        status = -1
    return status 

可以在上面的程序中使用return 1,return -1或return 0吗?而不是使用status = 0,1等等。我想以有效的方式处理程序中的错误。有人可以解释或告诉我该怎么做?

1 个答案:

答案 0 :(得分:0)

当然,您可以使用return而不是将状态分配给变量

def compare_files(file1, file2):
    try:
        with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
            if f_file1.read() == f_file2.read():
                print 'SUCCESS \n'
                return 0
            else:
                print 'FAILURE \n'
                return 1
    except IOError:
        print "[Error]File is NOT compared"
        return -1

你可能想要像这样处理它:

val = compare_files(file1, file2)
if val == 0:
    print "Files are the same"
elif var == 1:
    print "Files differ"
elif var == -1:
    print "Error"

但是这并没有给你任何关于错误导致status = -1

的信息