[Tutor] Why should modules or packages should define their own domain-specific base exception class?

bob gailer bgailer at gmail.com
Tue Apr 15 04:29:37 CEST 2014


On 4/14/2014 10:09 PM, brian arb wrote:
> I don't quite understand why the google python style guide recommends 
> that packages and modules we write should avoid using the catch-all 
> except. Instead the guide encourages you to write domain specific 
> exception classes.
>
> class Error(Exception):
>   """..."""
>
> class ThisSpecificError(Error):
> """..."""
>
> class ThatSpecificError(Error):
> """..."""
>
>
> try:
>   ...
> except mylib.Error:
>   ...
> |
> |
> |REF. 
> |http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Exceptions#Exceptions
>
> Thoughts?
Let's say I write a program to process some user input that should 
follow some syntatic / semantic rules. When my program finds a violation 
I want to raise an exception that is specific to these rules, rather 
than a built-in exception.

Raising such exceptions is a useful way to exit from some possibly 
deeply nested series of calls, ifs, whiles, fors, etc. I write except 
statements for my error classes, then let the python-specific ones be 
caught by a different except.

The python-specific exceptions mean something is wrong with my progam, 
which I handle differently than those related to user input.


More information about the Tutor mailing list