4

Web サイトからファイルをダウンロードするプログラムを実行しています。urllib.error.HTTPError を処理する 1 つの例外を導入しましたが、取得方法がわからない追加のエラーが時々発生しています: http.client.IncompleteRead. 一番下のコードに次を追加するだけですか?

except http.client.IncompleteRead:

プログラムが停止しないようにするには、いくつの例外を追加する必要がありますか? また、それらすべてを同じ 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.")
4

1 に答える 1

7

各例外タイプを個別に処理する場合は、個々の句を追加するexceptか、すべてを 1 つにまとめることができます。

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

以前に処理されなかったものをキャッチするジェネリック句を追加することもできます。

except Exception:

より有益なメッセージについては、発生した実際の例外を出力できます。

except Exception as x:
    print(x)
于 2013-08-31T04:37:50.313 に答える