4

I have some code which will make a requests.get() call, which may fail in various ways. I want to catch requests exceptions, but do not care about why the call failed.

I would like to avoid code like

try:
    r = requests.get(url)
except:
    pass

because it will possible catch exceptions which are not requests related (in the case above this would hardly be the case but if there was some more code it would be possible).

requests exceptions are documented but I would prefer not to list all of them. Is there a way to catch them all, some kind of wildcard on requests exceptions? (and more generally - for exceptions provided by a module)

I could also go for something like

try:
    r = requests.get(url)
except Exception as e:
    print(e)

but I would like to avoid analyzing e to filter out requests exceptions.

Note: this is not a duplicate of a question on handling all but one exception - I am targeting a whole class of related exceptions (and allow for a crash if something else raises an exception, which in my case would be a bug)

Community
  • 1
  • 1
WoJ
  • 27,165
  • 48
  • 180
  • 345
  • 1
    For `requests` you can always use `RequestsException` from which all inherit from what I can see. You can't work with exceptions that just might be defined in the same module (you could catch em all and filter out things in the `except` clause but that might get messy). – Dimitris Fasarakis Hilliard Mar 23 '17 at 14:49
  • Possible duplicate of [Handling all but one exception](http://stackoverflow.com/questions/16123529/handling-all-but-one-exception) – Marat Mar 23 '17 at 15:15
  • @Marat: this is not a duplicate - I want to catch a whole class of related exceptions, not "catch everything except one" (where I would just chain two `except` instances) – WoJ Mar 23 '17 at 15:19
  • 1
    @JimFasarakisHilliard: thank you, your comments covers both the `request` case (my immediate problem) and the general case (= it cannot be done, except filtering as I mentioned in my question). Would you mind turning this into an answer so that I can accept it? – WoJ Mar 23 '17 at 15:20

1 Answers1

2

Good library designers will usually create a base exception(s) for their library from which other exceptions will derive.

For requests this is RequestException according to the documentation you linked; using it in the except clause will catch anything that derives from it.

try:
    # code involving requests 
    # that might err
except RequestException:
    # ignore, handle..  

As stated in the comment and in the question, discriminating based on the module they are defined in cannot be done automatically (i.e in the except clause expression; you'd have to add that logic yourself in the body of the except clause.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253