I'm struggling to word this properly but here goes anyway.
If we know a specific exception will be thrown under certain circumstances, is it OK to catch that exception and not tell the user or log it anywhere? Or should an exception always be logged somewhere?
For example, let's say KeyError is expected under certain circumstances, e.g. if a dictionary that is created programmatically doesn't contain an item, yet. In one of my apps, I have that exact situation because the item that will eventually reside there hasn't been extracted from my XML file, yet. Until that time, I'm catching the KeyError, and carrying on knowing the KeyError eventually won't be thrown when I finish processing the XML. Terrible explanation, but I hope it makes sense.
Is that OK or would it be better practice to initialise the dictionary first, say in the class __init__ method so that the KeyError never happens, ever?
Thanks
except Exception:
pass
Python docs for the pass statement
Generic answer
The standard "nop" in Python is the pass statement:
try:
do_something()
except Exception:
pass
Using except Exception instead of a bare except avoid catching exceptions like SystemExit, KeyboardInterrupt etc.
Python 2
Because of the last thrown exception being remembered in Python 2, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of pass:
try:
do_something()
except Exception:
sys.exc_clear()
This clears the last thrown exception.
Python 3
In Python 3, the variable that holds the exception instance gets deleted on exiting the except block. Even if the variable held a value previously, after entering and exiting the except block it becomes undefined again.