Which exception to use?

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue Jan 28 17:43:49 EST 2003


On Tuesday 28 January 2003 13:09, Mongryong wrote:
> For 'library API', it's probably not a good idea to be checking the
> length of 'sys.argv'.  If you really need to check the length of
> 'some tuple' parameter, you might be better to use 'assert' instead.
>
> An exception should be used for cases where an 'expected' or
> 'undefine' runtime error occurs.  ie. Network connection failure.
>
> Assertions should be used for dumb programmer errors that would be
> trace-able through testing.

Well, actually, I define an arg_assert() that raises ArgumentError, and 
use that specifically to "assert" things about function/method 
arguments (ie, basically a pre-assertion).  What I like about that over 
using assert directly, is that I can use assert to verify internal 
state, and have a different error raised.  I don't (necessarily) want 
someone tryin to catch assertion errors that indicate that the software 
is in a bad state (ie. a bug), when they really only want to look out 
for API usage errors.

So, disregarding the sys.argv example (which was a followup from 
someone else's different example), I might choose to do something odd, 
like this (I apologize for the lameness of this example):


class ArgumentError( Exception ):
    pass

def arg_assert( predicate, msg="" ):
    if not predicate:
        raise ArgumentError, msg

# A silly illustrative example
class Spam:
    def __init__( self ):
        self._some_interval_variable = <some positive number>

    def eggs( self, x ):
        # Pretend we only will accept non-negative numbers
        arg_assert( x > 0, "argument to 'eggs()' must not be "
                           "negative." )

        # Could also test for numbers, strings convertable to float,
        # etc.

        # Now, let's assume there was an internal error,
        # then this assertion should catch it.
        assert self._some_internal_variable > 0

        # if not, do the work.
        <blah blah blah>

-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)





More information about the Python-list mailing list