ConnectionError handling problem
Jon Ribbens
jon+usenet at unequivocal.co.uk
Sun Sep 20 09:33:06 EDT 2015
On 2015-09-20, Chris Angelico <rosuav at gmail.com> wrote:
> On Sun, Sep 20, 2015 at 10:45 PM, Jon Ribbens
><jon+usenet at unequivocal.co.uk> 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.
>
> General principle: If you don't know what you should be catching,
> _catch nothing_. Anything that happens will get printed to the
> console. Then when you find that something's getting thrown, you check
> out what its name is, and maybe what its superclasses are (in case
> there's a broader one worth catching), and only THEN do you stick in a
> try/except.
I'm afraid I think that's absolutely terrible advice. I agree that
you should not be afraid to let exceptions propagate up the stack
(one of the things that's disastrously wrong about Java) but the
case at hand of "try and fetch this network resource and then do
something if it didn't succeed" is perfectly reasonable, and trying to
code that by trial and error is a perfect example of bad programming.
More information about the Python-list
mailing list