0

I'm new to Python and I want to know the best way to handle the following error:

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

If I set a wrong name I get this error:

dropbox.rest.ErrorResponse: [404] u'File not found'

I could write a function to check if the file exists but I want to know If I can handle it in a better way.

geckon
  • 8,316
  • 4
  • 35
  • 59
AFS
  • 1,433
  • 6
  • 28
  • 52

2 Answers2

1

I assume you want to try to open the file and if this fail, prompt the user to try again?

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

As pointed out by @SuperBiasedMan and @geckon, you are trying to call client.get_file_and_metadata and, if this fails with exception dropbox.rest.ErrorResponse, handling this in some way. In this case the error handling code checks if the error is 404 (file missing) and tells the user to try a different file. As filefound = False, it results in another prompt to the user again. If the error is not file missing, the error is raised and the code stops.

Ed Smith
  • 12,716
  • 2
  • 43
  • 55
  • Worth explaining that it's considered Pythonic to catch specific errors and deal with them rather than actually letting the program raise the errors. – SuperBiasedMan May 14 '15 at 17:05
0

To append something to Ed Smith's answer, I would like to recommend you to read something about exceptions and their handling in general. You might know them from another languages like C++ or Java as well, but if you're new to programming, you should know about the concept and it's advantages.

Community
  • 1
  • 1
geckon
  • 8,316
  • 4
  • 35
  • 59