Link to home
Start Free TrialLog in
Avatar of Mehan CO
Mehan COFlag for United States of America

asked on

pass error on python3

i got this error while running my script  
 requests.exceptions.ConnectionError

Open in new window

, now i want create except for it  , is this way is true ?

except (BaseException, Exception, AttributeError, requests.exceptions.ConnectionError, ConnectionError) as err:
                    pass

Open in new window

Avatar of gelonida
gelonida
Flag of France image

Well if you only want to capture ConnectionErrors, then you should write


except requests.exceptions.ConnectionError:

Open in new window


(you have of course to import requests to make this work)


Of course I don't know the context of your error / your issues, but in many cases it makes sense to add a log statement / a print statement or
to add an error counter or a list of failed urls in the except statement.
Otherwise debugging will be very tricky if you just silent this exception.
Avatar of Mehan CO

ASKER

then my job is Okey ?

except (BaseException, Exception, AttributeError, requests.exceptions.ConnectionError, ConnectionError) as err:

Open in new window

As I said the line should be working to catch your exception (except the exception occurred in a thread or sub process)


But your line is way too complicated:


if you write
except Exception, BaseException:
     pass

Open in new window


you have probably the same result:

just add in your code something like:
excs = (BaseException, Exception, AttributeError, requests.exceptions.ConnectionError, ConnectionError)
for exc in excs:
     print(isinstance(exc(""), Exception), exc)

Open in new window

you will probably get a result similiar to:
(False, <type 'exceptions.BaseException'>)
(True, <type 'exceptions.Exception'>)
(True, <type 'exceptions.AttributeError'>)
(True, <class 'requests.exceptions.ConnectionError'>)
(True, <class 'requests.exceptions.ConnectionError'>)

this means, that AttributeError requests.exceptions.ConnectionError are subclasses of Exception.

so if you catch Exception you do not have to  explicitly cacth AttributeError requests.exceptions.ConnectionError


if you want to catch all exceptions (though this is depending on the context not necesasiry good practice , then better to just write


except:
    pass

Open in new window



If you want to catch all but one exception then:
try:
    your_code_with_exception
except ExceptionYouDontWantToCatch:
    raise
except: # catch all other exceptions
    print("rest caught here"

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.