Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent "too broad exception" in this case?

I have a list of functions that may fail and, if one fails, I don't want the script to stop, but to continue with next function.

I am executing it with something like this :

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

It's working fine, but it is not PEP8 compliant:

When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.

For example, use:

try:     import platform_specific_module except ImportError:     platform_specific_module = None 

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException: ).

A good rule of thumb is to limit use of bare 'except' clauses to two cases:

If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.

If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise . try...finally can be a better way to handle this case.

How can I do this the good way?

like image 351
Blusky Avatar asked May 25 '15 16:05

Blusky


People also ask

How do you raise an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

Why would you raise an exception?

By raising a proper exception, it will allow other parts of your code to handle the exception properly, such that the execution can proceed. In the above code, we first define a function, read_data , that can read a file.

How do you catch errors in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.


2 Answers

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) 
like image 103
Ed Smith Avatar answered Sep 29 '22 22:09

Ed Smith


Use this to cheat PEP8:

try:     """code"""  except (Exception,):      pass 
like image 23
Allex Radu Avatar answered Sep 29 '22 21:09

Allex Radu