Exception Handling Practices / Patterns

Dave Angel davea at davea.name
Sat Aug 24 03:18:59 EDT 2013


snarf wrote:

> Greetings,
>
> As I tread through my journey of OO I am trying to determine if there is a good approach for exception handling within classes.
>
> From my readings and gatherings - it seems I have found a common theme, but I am trying to solicit from the experts.
>
> Here is what I have found (I may be restating the obvious so please forgive me in advance):
>
> * Seems like exception handing within Classes is largely avoided and is typically only used when calling external libraries.
> * Try/Except type statements seem to be used more within modules, main functions, wrapper scripts.

Exceptions are used when useful.  I don't see any bias towards any one
location.

> * Classes should be coded in a way that exceptions 

You seem to be missing the last part of this sentence.

> * Better to never write your own exceptions (unless you absolutely have to).

If you mean to avoid writing exception classes, then I say nonsense. 
Just derive them from the closest meaningful exception class, so that a
user can combine handlers when reasonable.

> * Using Exception is typically a bad. More specific the better.

If you mean in an except statement, then I'd agree.

> * Exceptions should never fail silently. (Should exceptions always be logged?)

Exceptions should be caught if you can handle them, or if you need to
convert them to a different exception that someone further up the stack
can handle.  Sometimes handling means do nothing.

>
> Best site I have found for exceptions (hopefully this helps someone):
> * http://c2.com/cgi/wiki?ExceptionPatterns

But that's for Java.  java is not C++, and neither is it Python.  For
one thing, Python exception overhead is deliberately much less, and they
are used more freely.

Notice that exceptions are used to terminate for loops, and that's a
*normal* exit to the loop.  They also appear in other places under the
covers.  Don't be afraid of them.

-- 
DaveA





More information about the Python-list mailing list