I'm writing an exception clause at the top level of a script, and I just want it to log whatever errors occur. Annoyingly, PyCharm complains if I just catch Exception
.
import logging
logging.basicConfig()
try:
raise RuntimeError('Bad stuff happened.')
except Exception: # <= causes warning: Too broad exception clause
logging.error('Failed.', exc_info=True)
Is there something wrong with this handler? If not, how can I tell PyCharm to shut up about it?
From a comment by Joran: you can use # noinspection PyBroadException
to tell PyCharm that you're OK with this exception clause. This is what I was originally looking for, but I missed the option to suppress the inspection in the suggestions menu.
import logging
logging.basicConfig()
# noinspection PyBroadException
try:
raise RuntimeError('Bad stuff happened.')
except Exception:
logging.error('Failed.', exc_info=True)
If you don't even want to log the exception, and you just want to suppress it without PyCharm complaining, there's a new feature in Python 3.4: contextlib.suppress()
.
import contextlib
with contextlib.suppress(Exception):
raise RuntimeError('Bad stuff happened.')
That's equivalent to this:
try:
raise RuntimeError('Bad stuff happened.')
except Exception:
pass