6

I'm running a program that downloads files from a web sit. I've introduced one exception handling urllib.error.HTTPError, but now I'm getting from time to time additional errors that I'm not sure how to capture: http.client.IncompleteRead. Do I just add the following to the code at the bottom?

except http.client.IncompleteRead:

How many exceptions do I have to add to make sure the program doesn't stop? And do I have to add them all in the same Except statement or in several Except statements.

try:
   # Open a file object for the webpage 
   f = urllib.request.urlopen(imageURL)
   # Open the local file where you will store the image
   imageF = open('{0}{1}{2}{3}'.format(dirImages, imageName, imageNumber, extension), 'wb')
   # Write the image to the local file
   imageF.write(f.read())
   # Clean up
   imageF.close()
   f.close()

except urllib.error.HTTPError: # The 'except' block executes if an HTTPError is thrown by the try block, then the program continues as usual.
   print ("Image fetch failed.")

1 Answer 1

8

You can add individual except clauses if you want to handle each exception type separately, or you could put them all in one:

except (urllib.error.HTTPError, http.client.IncompleteRead):

You can also add a generic clause that will catch anything not handled previously:

except Exception:

For more informative messages, you can print the actual exception that happens:

except Exception as x:
    print(x)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. What will happen if the exception was caused by an inability to close the file or download the file, or other mishaps? Should I try to close the file as part of the code immediately following the except statement?
@gciriani: You can use the finally clause to help ensure files are closed, or use the with statement which is a nicer way of doing that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.