Python HTTP异常处理 [英] Python HTTP Exception Handling

查看:317
本文介绍了Python HTTP异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个从网站下载文件的程序。我引入了一个异常处理urllib.error.HTTPError,但是现在我不定期地收到我不确定如何捕获的其他错误:http.client.IncompleteRead。我只需将下面的代码添加到底部的代码中。

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.")


推荐答案

p>如果要单独处理每个异常类型,您可以添加单独的,除了子句,也可以将它们全部放在一起:

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)

这篇关于Python HTTP异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆