close

How to prevent “too broad exception” in this case?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to prevent “too broad exception” in this case in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to prevent “too broad exception” in this case?

  1. How to prevent “too broad exception” in this case?

    The PEP8 guide you quote suggests that it is okay to use a bare exception in your case provided you are logging the errors.

  2. prevent “too broad exception” in this case

    The PEP8 guide you quote suggests that it is okay to use a bare exception in your case provided you are logging the errors.

Method 1

The PEP8 guide you quote suggests that it is okay to use a bare exception in your case provided you are logging the errors. I would think that you should cover as many exceptions as you can/know how to deal with and then log the rest and pass, e.g.

import logging

list_of_functions = [f_a,f_b,f_c]
for current_function in list_of_functions:
    try:
        current_function()
    except KnownException:
        raise
    except Exception as e:
        logging.exception(e)

Method 2

I think in some rare cases catching general exception is just justified and there is a way to trick PEP8 inspection:

list_of_functions = [f_a,f_b,f_c]
for current_function in list_of_functions:
try:
    current_function()
except (ValueError, Exception):
    print(traceback.format_exc())

You can replace ValueError by any other. It works for me (at least in PyCharm).

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read