What are the best practices for creating exceptions? I just saw this, and I don\'t know if I should be horrified, or like it. I read several times in books that exceptions shoul
Robust exception handling (in Python) - a "best practices for Python exceptions" blog post I wrote a while ago. You may find it useful.
Some key points from the blog:
Never use exceptions for flow-control
Exceptions exist for exceptional situations: events 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.
Handle exceptions at the level that knows how to handle them
...
The best place is that piece of code that can handle the exception. For some exceptions, like programming errors (e.g. IndexError, TypeError, NameError etc.) exceptions are best left to the programmer / user, because "handling" them will just hide real bugs.
Always ask "is this the right place to handle this exception?" and be careful with catching all exceptions.
Document the exceptions thrown by your code
...
thinking about which exceptions your code may throw will help you write better, safer and more encapsulated code