如何处理和设置错误,return 和 return 中的值 python?
how to handle and set the error, return and return value in python?
我是编程新手,有人能告诉我有什么区别以及如何处理 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
是否可以在上面的程序中使用return1、return-1或return0?而不是使用 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"
但这并没有给你任何关于错误原因的信息 status = -1
我是编程新手,有人能告诉我有什么区别以及如何处理 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
是否可以在上面的程序中使用return1、return-1或return0?而不是使用 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"
但这并没有给你任何关于错误原因的信息 status = -1