Exception handling wart in Python

David Abrahams david.abrahams at rcn.com
Sat Nov 3 16:25:14 EST 2001


"Leo Lipelis" <aeoo at myspamrealbox.com> wrote in message
news:pan.2001.11.02.09.15.54.147.704 at myspamrealbox.com...
> Besides, I am not looking to duplicate Java by enforcing exceptions.  Even
> Java itself doesn't enforce *all* exceptions.  Java has the unenforced
> RuntimeException. Although you could *only* throw RuntimeException's if
you
> wanted, it would be bad programming practice.  Thus, Java is not a fascist
> dictator.  Java does it's own thing, and it's fine.  Python has a
different
> flavour.  I think Python should provide a standard tool that gives
warnings
> about unhandled exceptions (maybe not all, but as many as possible).
> Invoking this tool would be up to the programmer.  For small scripts it
> wouldn't even make sense to use it.  But for a large code base, it would
be
> a great tool.

We in the C++ world have learned a lot about what it takes to make a robust
program that uses exceptions. Python's EH mechanism is almost identical to
that of C++, and most of the same rules apply. In general it is not so
important to know exactly which exceptions can be thrown -- you can always
handle anything with except: (or catch(...) in C++); all that's lost is the
ability to report errors accurately. That's a loss, but not as serious a
loss as what you give up when you don't know:

A. Exactly which operations can fail.
B. What you can count on about the program state in case of a failure. For
example, if I run out of memory when appending to a list, is the list
unmodified? Empty? Unspecified?

Java's specification goes to great lengths to enumerate (some of) the
exceptions that can be thrown, but never says whether or how the program
state has changed in case of a failure. That, combined with the fact (IIRC)
that an "asynchronous exception" can appear magically at any point in your
program's execution makes true exception-safety in Java next to impossible.

Python in general tends to be underspecified, but if you want to add rigor
in the area of exception-handling, I suggest concentrating on dividing
operations according to one of three distinctions:

1. basic guarantee -- all invariants of the object(s) being operated on are
preserved; no resources are leaked. This is the bare minimum.
2. strong guarantee -- if an exception is thrown, the program state is
unchanged
3. nothrow guarantee -- the operation can't fail

With these 3, you have the tools you need to construct programs that can
effectively and reliably recover from error conditiions.

-Dave

--
===================================================
  David Abrahams, C++ library designer for hire
 resume: http://users.rcn.com/abrahams/resume.html

        C++ Booster (http://www.boost.org)
          email: david.abrahams at rcn.com
===================================================






More information about the Python-list mailing list