0

Does anyone have a cleaner way to handle exceptions in Python?

Currently I frequently have this pattern in my code

try:
    #some code that throws an exception
except:
    pass #because I don't really need to handle anything in this case

Is there a way just to catch the exception without doing this? Any Suggestions?

In this specific case, I am using selenium and depending on if a page element is there or not I need to execute some code. If it's not there, an exception is thrown but the code may continue. I simply am seeing if there is a cleaner way to handle this :)

MrRoboto
  • 825
  • 3
  • 11
  • 14
  • 1
    To catch exceptions you need a `try...except`; but you generally would only catch **specific** exceptions. – Martijn Pieters Aug 06 '14 at 14:16
  • 1
    In Python 3.4: [`contextlib.suppress`](https://docs.python.org/dev/library/contextlib.html#contextlib.suppress), although you have to specify errors (which is good practice - see e.g. [here](http://blog.codekills.net/2011/09/29/the-evils-of--except--/)) – jonrsharpe Aug 06 '14 at 14:17
  • Thanks for the tip on 3.4, I'm on 2.7 with this project. – MrRoboto Aug 07 '14 at 03:22

0 Answers0