Python HTTP 异常处理

gci*_*ani 4 python exception-handling

我正在运行一个从网站下载文件的程序。我已经介绍了一个异常处理 urllib.error.HTTPError,但现在我不时遇到其他我不确定如何捕获的错误:http.client.IncompleteRead。我是否只需将以下内容添加到底部的代码中?

except http.client.IncompleteRead:
Run Code Online (Sandbox Code Playgroud)

我必须添加多少个例外才能确保程序不会停止?并且我是否必须将它们全部添加到同一个Except 语句或多个Except 语句中。

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.")
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 6

except如果您想分别处理每种异常类型,您可以添加单独的子句,或者您可以将它们全部放在一起:

except (urllib.error.HTTPError, http.client.IncompleteRead):
Run Code Online (Sandbox Code Playgroud)

您还可以添加一个通用子句来捕获以前未处理的任何内容:

except Exception:
Run Code Online (Sandbox Code Playgroud)

如需更多信息性消息,您可以打印实际发生的异常:

except Exception as x:
    print(x)
Run Code Online (Sandbox Code Playgroud)