What are the best practices for exception handling in Python?

PythonServer Side ProgrammingProgramming

Some of the best practices for exception handling in python are given below:

Exceptions are better than returning error status codes. We have to handle exceptions in Python as the whole language core and standard libraries throw exceptions. Elegantly handled exceptions are any day preferable to error codes and trace backs.

It is wise thing not to use exceptions for flow-control.

Exceptions arise in exceptional situations that are not a part of normal execution.

Consider 'find' on a string returning -1 if the pattern isn't found, but indexing beyond the end of a string raises an exception. Not finding the string is normal execution.

It is better we handle exceptions at the level that we know how to handle them

The best place is that piece of code that can handle the exception. For some exceptions, like programming errors (like IndexError, TypeError, NameError etc.) exceptions are best left to the programmer, because "handling" them may hide real bugs.

Always we should ask "is this the right place to handle this exception?" and be careful with catching all exceptions.

We should document the exceptions thrown by our code. Thinking about which exceptions our code may throw will help us write better, safer and more encapsulated code.

Published on 07-Dec-2017 11:08:49