Article 52P9Q Exception handling in Python

Exception handling in Python

by
Turbocapitalist
from LinuxQuestions.org on (#52P9Q)
I'm wondering how to trap exceptions in Python. Specifically, when I run this code:

Code:#!/usr/bin/python3

import urllib.request

uri = 'http://localhost:1880/'
req = urllib.request.Request(uri,method="HEAD",data=None)

with urllib.request.urlopen(uri) as response:
try:
res = response.read()
except HTTPError as e:
print("HTTP error")
except URLError as e:
print("URL error")
except TypeError as e:
print("Type error")
except ValueError as e:
print("Value error")and try to connect it to a session which will abort,

Code:timeout 2 nc -l 1880 & ./script.pythen I always get the following crash report:

Code:GET / HTTP/1.1
Accept-Encoding: identity
Host: localhost:1880
User-Agent: Python-urllib/3.7
Connection: close

Traceback (most recent call last):
File "./script.py", line 10, in <module>
with urllib.request.urlopen(uri) as response:
File "/usr/lib/python3.7/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.7/urllib/request.py", line 525, in open
response = self._open(req, data)
File "/usr/lib/python3.7/urllib/request.py", line 543, in _open
'_open', req)
File "/usr/lib/python3.7/urllib/request.py", line 503, in _call_chain
result = func(*args)
File "/usr/lib/python3.7/urllib/request.py", line 1345, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "/usr/lib/python3.7/urllib/request.py", line 1320, in do_open
r = h.getresponse()
File "/usr/lib/python3.7/http/client.py", line 1336, in getresponse
response.begin()
File "/usr/lib/python3.7/http/client.py", line 306, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.7/http/client.py", line 275, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without responseWhat is the right way to catch that error so the script can make note of it and continue? Right now the script just dies.latest?d=yIl2AUoC8zA latest?i=CZ2qWg_a4fY:adu1goWwik4:F7zBnMy latest?i=CZ2qWg_a4fY:adu1goWwik4:V_sGLiP latest?d=qj6IDK7rITs latest?i=CZ2qWg_a4fY:adu1goWwik4:gIN9vFwCZ2qWg_a4fY
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments