[Tutor] How to notify/handle an error?

Alan Gauld alan.gauld at btinternet.com
Sun Oct 31 17:52:01 CET 2010


"dave p. guandalino" <guandalino at gmail.com> wrote

> Which of the following ways is better to handle something wrong?

Its not really a questin of "better" but a question of more idiomatic.

> def is_valid_project():
>    # Do checks and valorize is_a_valid_project accordingly
>    return is_a_valid_project # True / False

This is a good return value given the functions name - it suggests
it is a predicate so should return a boolean result.

> def is_valid_project():
>    # Do checks and valorize is_a_valid_project accordingly
>    if not is_a_valid_project:
>        raise NotAValidProject

This is not showing what the return value is but one assumes
it is True if the project is valid, but raises an exception if not 
valid.
That mixed response is not good for a predicate. But if you
renamed the function to validate_project(p) that returns None
if OK and raises an exception for an invalid project that might
be considered acceptable.That would resuult in code like:

try:
    validate_project(p)
    pass # do stuff with project p
except InvalidProjectError:
    HandleError()

But a lot depends on what the tests look like. True exception
based error handling would simply assume the project was
valid, proceed to process it and only raise an exception if
the processing failed. This probably obviates the need for the
check function entirely... So...

> try:
>    is_valid_project()
>    pass # do stuffs with valid project
> except NotAValidProject:
>    print "error"

becomes

try:
    pass # do stuffs with valid project
except <list of possible errors>:
    HandleError()

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list