我是Python的新手,我想知道处理以下错误的最佳方法:
downloaded = raw_input("Introduce the file name: ").strip()
f, metadata = client.get_file_and_metadata('/'+downloaded)
#print 'metadata: ', metadata['mime_type']
out = open(downloaded, 'wb')
out.write(f.read())
out.close()
如果我设置了错误的名称,我会收到此错误:
dropbox.rest.ErrorResponse: [404] u'File not found'
我可以编写一个函数来检查文件是否存在,但我想知道如果我能以更好的方式处理它。
答案 0 :(得分:1)
我假设你想尝试打开文件,如果失败,提示用户再试一次?
filefound = False
while not filefound:
downloaded = raw_input("Introduce the file name: ").strip()
try:
f, metadata = client.get_file_and_metadata('/'+downloaded)
#print 'metadata: ', metadata['mime_type']
filefound = True
except dropbox.rest.ErrorResponse as e:
if e.status == 404:
print("File " + downloaded + " not found, please try again")
filefound = False
else:
raise e
out = open(downloaded, 'wb')
out.write(f.read())
out.close()
正如@SuperBiasedMan和@geckon指出的那样,你试图调用client.get_file_and_metadata
,如果失败而异常dropbox.rest.ErrorResponse
,则以某种方式处理它。在这种情况下,错误处理代码检查错误是否为404(文件丢失)并告诉用户尝试使用其他文件。如filefound = False
,它会再次向用户发出另一个提示。如果错误不是文件丢失,则会引发错误并停止代码。
答案 1 :(得分:0)
要向Ed Smith's answer附加内容,我建议您一般阅读something about exceptions and their handling。您可能也会从其他语言(如C ++或Java)中了解它们,但如果您不熟悉编程,则应了解概念及其优点。