error handling in Python

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed May 5 19:26:02 EDT 2004


<beliavsky at aol.com> wrote in message
news:3064b51d.0405050741.43d11aa0 at posting.google.com...
>
> I do NOT want to use the try/except idiom to stop the program if there
> is a problem reading data.
>
Unlike FORTRAN, exceptions in Python do not necessarily stop the program -
they only do so if not handled.

In your case, you know just where read_data() is called from, so you can
catch a thrown exception and do the appropriate
cleanup/retry/shutdown/ignore-and-continue, all without having to figure out
what "special" value to put in the return code to indicate a failure.  You
also don't have to clutter up your read_data() argument list with error
codes, error descriptions, I/O status, etc. - put that stuff in attributes
of the thrown exception, and leave your read_data() arguments to deal with
the read_ing of data.

Don't try to hack around try-except's mechanisms for invoking exception
code, by using magic return codes ("if zero, that means success; if greater
than zero, that's a warning; less than zero is an error") and exception-only
method arguments.  Cleaning this stuff out of your method signature is a
*good* thing, and let's you focus on the functional task, while try-except
offers a clear, robust, supported mechanism for signalling, um, let's not
call them "failures", how about "alternative return paths"?  :)

-- Paul






More information about the Python-list mailing list