Avoiding "Too broad exception clause" warning in PyCharm
I am reluctant to turn off warnings as a matter of principle.
In the case presented, you know well what the exception is. It might be best to just be specific. For example:
try: raise RuntimeError("Oops") except RuntimeError as e: print(e, "was handled")
will yield "Oops was handled".
If there are a couple of possible exceptions, you could use two except clauses. If there could be a multitude of possible exceptions, should one attempt to use a single try-block to handle everything? It might be better to reconsider the design!
Not sure about your PyCharm version (mine is 2019.2), but I strongly recommend disabling this PyCharm inspection in File> Settings> Editor> Inspections and type "too broad". In Python tab, deselect "too broad exceptions clauses" to avoid those. I believe this way PyCharm would show you the correct expression inspection
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