Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding "Too broad exception clause" warning in PyCharm

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?

like image 575
Don Kirkby Avatar asked Nov 23 '16 23:11

Don Kirkby


3 Answers

I found a hint in this closed feature request for PyCharm:

I suggest you to mark this inspection as 'okay' if the except block makes use of exception instance e somehow.

Because I'm logging with exc_info=True, I'm implicitly using the current exception object, but PyCharm doesn't know that. To make it explicit, I can pass the exception object to exc_info. Since Python 3.5, the logger methods have accepted an exception instance to report, as well as accepting any truthy value to report the current exception and stack trace in the log.

import logging

logging.basicConfig()

try:
    raise RuntimeError('Bad stuff happened.')
except Exception as e:
    logging.error('Failed.', exc_info=e)
like image 165
Don Kirkby Avatar answered Nov 19 '22 05:11

Don Kirkby


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!

like image 5
DeanM Avatar answered Nov 19 '22 03:11

DeanM


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

like image 4
Daniel Serretti Avatar answered Nov 19 '22 05:11

Daniel Serretti