python中的处理错误

2024-04-26 14:18:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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()

如果我设置了一个错误的名字,我会得到这个错误:

^{pr2}$

我可以编写一个函数来检查文件是否存在,但我想知道是否可以用更好的方式处理它。在


Tags: the方法nameclientinputgetraw错误
2条回答

为了给Ed Smith's answer添加一些内容,我建议您大致阅读something about exceptions and their handling。你可能会从其他语言中了解到它们,比如C++和java,但是如果你是新的编程人员,你应该知道这个概念和它的优点。在

我假设您想尝试打开文件,如果失败,提示用户再试一次?在

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,它会再次向用户发出另一个提示。如果错误不是文件丢失,则引发错误并停止代码。在

相关问题 更多 >