Should I always specify an exception type in `except` statements?

前端 未结 7 1311
广开言路
广开言路 2020-11-22 15:33

When using PyCharm IDE the use of except: without an exception type triggers a reminder from the IDE that this exception clause is Too broad.

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 15:52

    You should not be ignoring the advice that the interpreter gives you.

    From the PEP-8 Style Guide for Python :

    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.

提交回复
热议问题