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

前端 未结 7 1327
广开言路
广开言路 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 16:02

    Here are the places where i use except without type

    1. quick and dirty prototyping

    That's the main use in my code for unchecked exceptions

    1. top level main() function, where i log every uncaught exception

    I always add this, so that production code does not spill stacktraces

    1. between application layers

    I have two ways to do it :

    • First way to do it : when a higher level layer calls a lower level function, it wrap the calls in typed excepts to handle the "top" lower level exceptions. But i add a generic except statement, to detect unhandled lower level exceptions in the lower level functions.

    I prefer it this way, i find it easier to detect which exceptions should have been caught appropriately : i "see" the problem better when a lower level exception is logged by a higher level

    • Second way to do it : each top level functions of lower level layers have their code wrapped in a generic except, to it catches all unhandled exception on that specific layer.

    Some coworkers prefer this way, as it keeps lower level exceptions in lower level functions, where they "belong".

提交回复
热议问题