all Python 3http.clientexception
http.client.HTTPException
exceptions
The base class of every exception in http.client. It catches protocol errors but not socket-level network errors.
Syntax
except http.client.HTTPException as e: ...
except HTTPException will not catch a refused connection, a timeout or a socket-level drop: those are OSError and its subclasses (ConnectionRefusedError, TimeoutError). A robust handler catches both: except (http.client.HTTPException, OSError). The exception is RemoteDisconnected: it inherits both BadStatusLine and ConnectionResetError, so either branch catches it. A 404 or 500 response is not an exception at all.
Examples
import http.client
print(issubclass(http.client.LineTooLong, http.client.HTTPException)) # → True
print(issubclass(ConnectionRefusedError, http.client.HTTPException)) # → False
print(issubclass(http.client.RemoteDisconnected, OSError)) # → True
import http.client
import socket
server, client = socket.socketpair()
server.sendall(b'garbage\r\n')
server.close()
resp = http.client.HTTPResponse(client)
try:
resp.begin()
except http.client.HTTPException as e:
print(type(e).__name__) # → BadStatusLine
client.close()
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy