ConnectionError handling problem

Jon Ribbens jon+usenet at unequivocal.co.uk
Sun Sep 20 15:28:51 CEST 2015


On 2015-09-20, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
> On 20/09/2015 13:45, Jon Ribbens wrote:
>> On 2015-09-19, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
>>> On 19/09/2015 07:13, shiva upreti wrote:
>>>> 		try:
>>>> 			r=requests.post(url, data=query_args)
>>>> 		except:
>>>> 			print "Connection error"
>>>
>>> Never use a bare except in Python, always handle the bare minimum number
>>> of exceptions that you need to, in this case your ConnectionError.
>>
>> While I entirely agree with the principle of being specific in what
>> exceptions you are catching (with the absolute maximum being
>> 'Exception'), it is often not obvious which ones you need to specify.
>> The code above probably actually needs to catch EnvironmentError if
>> it is intended to intercept all network problems.
>
> I doubt it, as from the docs "The following exceptions are kept for 
> compatibility with previous versions; starting from Python 3.3, they are 
> aliases of OSError.".  EnvironmentError is one of those listed.  I'd 
> have thought it far more likely that you'd want to catch one or more of 
> the OSError subclasses, as finer grained exceptions was part of the 
> rationale behind PEP 3151 -- Reworking the OS and IO exception hierarchy.

PEP 3151 has nothing to do with it, as the code in question in this
thread is running under Python 2 not Python 3. If you catch only
OSError then you will miss almost all the likely exceptions raised
by requests.


More information about the Python-list mailing list