6 Exceptionally Common Pitfalls of Python Exception Handling

There’s a little more to remember than try..except

Andrew Scott
Analytics Vidhya

--

Based on photo by Hugo Jehanne on Unsplash

1. Generic Error Catching

This one is extremely common to see, either due to developer laziness, or misunderstanding. A generic catch-all means that all python exceptions will be caught, not just those that inherit from Exception. The significance of this is that some types of exceptions you may not want to catch will still be caught, such as KeyboardInterrupt or other top-level exceptions. In some cases this can make it very difficult to kill a running script.

What you probably mean to do here is except Exception as e, which will catch most all exceptions that inherit from Exception. This includes most programming errors, such as KeyErrors, ValueError, and so on. However, even this isn’t really encouraged. Instead you should always try to narrow your exception handling down to be as specific as possible based on the code in your try block. When in doubt about inheritance, you can always reference this handy exception hierarchy.

--

--

Andrew Scott
Analytics Vidhya

Maintainer @OchronaSec | PANW, ex Expanse, ex Tenable | Security & Automation | All views are my own... and awesome