Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

What are the best practices for exception handling in Python?

I have come across this idea that exceptions should not hold strings, as strings can themselves throw exceptions. How far is this idea true?


1 Answer
Manogna

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.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.