Python HTTP Exception Handling

2024/10/18 12:09:57

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 imageimageF = open('{0}{1}{2}{3}'.format(dirImages, imageName, imageNumber, extension), 'wb')# Write the image to the local fileimageF.write(f.read())# Clean upimageF.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.")
Answer

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)
https://en.xdnf.cn/q/72961.html

Related Q&A

Weird lambda behaviour in loops [duplicate]

This question already has answers here:What do lambda function closures capture?(8 answers)Closed 10 years ago.I stumbled upon a behaviour in python that I have a hard time understanding. This is the…

Why does inspect return different line for class inheriting from superclass?

While trying to figure out if a function is called with the @decorator syntax, we realized that inspect has a different behaviour when looking at a decorated class that inherits from a superclass.The f…

Sorting a list of tuples with multiple conditions

I am currently trying to sort the following list:list_ = [(1, 0101), (1, 1010), (1, 101), (2, 01), (2, 010), (2, 10)]These are the steps I want to take in order to sort it:Sort the list by the value of…

Tensorboard error: Tensor object has no attribute value

My goal: Add arbitrary text to tensorboard.My code:text = "muh teeeext" summary = tf.summary.text("Muh taaaag", tf.convert_to_tensor(text)) writer.add_summary(summary)My error:File …

How to embed Google Speech to Text API in Python program? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

shell script remote execution using python

Is there a way that I can use Python on Windows to execute shell scripts which are located on a remote Unix machine?P.S: Sorry about the late edit. I do know of Paramiko, but I wanted to know if there…

Shutdown for socketserver based Python 3 server hangs

I am working on a "simple" server using a threaded SocketServer in Python 3.I am going through a lot of trouble implementing shutdown for this. The code below I found on the internet and shut…

How do I url encode in Python?

I tried this: but it doesnt work.print urllib.urlencode("http://"+SITE_DOMAIN+"/go/")I want to turn it into a string with url encodings

resampling pandas series with numeric index

suppose I have a pandas.Series with index with numeric value type e.g. pd.Series( [10,20], [1.1, 2.3] )How do we resample above series with 0.1 interval? look like the .resample func only work on date…

Python3 Tkinter popup menu not closing automatically when clicking elsewhere

Im running Python 3.3.3 (and right now Im on Ubuntu but I also develop on Mac and Windows, which I havent yet tested). I have a Treeview object that responds to right click on items and shows a context…