How to effectively use exception

Alex Martelli aleaxit at yahoo.com
Sat Apr 14 15:14:49 EDT 2001


"Steven Haryanto" <steven at haryan.to> wrote in message
news:mailman.987246861.25847.python-list at python.org...
    [snip]
> First, should we use exceptions whenever possible? For example,

No.  You can build many other control structures out of
exeptions, but just because you can it is not a good reason
to do so.  break, return, etc, are better when suitable,
*because* they're less general and more specific.

> should a smallish function that do some testing return 1/0 to
> indicate success/failure or should it raise ValueError if the
> test fails? Is the try-except-else style more Pythonic/
> recommended than the if-else-then style? If not, what are the
> considerations to balance the two?

If it is an error for the check to fail, and you want to make
sure client-code won't accidentally forget to check a return
value, then THAT is a good reason to have the function
raise an exception if needed.  If the ONLY purpose of the
function is the 'testing', such forgetfulness is not to be
feared -- for example, see builtin functions such as
isinstance, callable, hasattr: they all return 1 or 0, since
they are called for the sole purpose of checking -- their
boolean results make for more natural conjunction, e.g.
with operators such as or, and, not, within an if or elif.


> Second, when do we create our own specific Exception classes,
> and when do we just use the existing standard Exception (I use
> ValueError in a lot of my methods & functions, accompanied by
> the specific message string. So far I haven't faced with the
> need to create a custom Exception class).

except clauses have an easy time catching specific exception
classes; if you raise your own specific class (which may derive
from ValueError, or whatever), you may ease life for authors
of client code (including yourself:-).  You _need_ to have your
own classes if they must carry special data fields, but that is
a pretty rare issue.


> Lastly, can someone recommend some readings on this matter?

On the MSDN, last year, there was an excellent series on error
handling in C and C++ (on the "Exceptional C++" column); I
think you can still find them.  They're *NOT* fully applicable to
Python, alas, but at least they give you good grounding (if you
have a strong C/C++ background) in a different language's style
of exception use -- reasoning by difference from it may be
easier than trying to reason things out in a vacuum.


Alex






More information about the Python-list mailing list