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

标签 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等等。我想以有效的方式处理程序中的错误。有人可以解释或告诉我该怎么做吗?

最佳答案

当然,您可以使用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"

但这并没有为您提供任何有关导致错误的状态= -1的信息。

关于python - 如何处理和设置错误,返回并在python中返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35919799/

相关文章:

python - 如何删除 Pandas 中的小数点

python - 此代码在我的计算机上有效,但在 leetcode 中无效

bash - 如何使用-e检查bash中的错误

python - 如何通过更改时间段来计算唯一出现次数分组?

python - happybase连接hbase获取表信息失败

python - 如何在python中的while循环语句中使用迭代器

mysql - #1064 - 您的 SQL 语法有误;查看与您的 MySQL 服务器版本对应的手册

python - 如何从实验室图像中删除 L channel

python - 函数属性

r - 在group_by中调用cor函数的`The standard deviation is zero`错误