Identifying exceptions that can be raised

Dan Sommers me at privacy.net
Sat Nov 20 08:06:04 EST 2004


On Sat, 20 Nov 2004 07:18:32 GMT,
Andrew Dalke <adalke at mindspring.com> wrote:

> Peter Hansen wrote:
>> Nope.  That's that nasty ol' Java thinkin'. ;-)
>> Basically, given the dynamicism that is Python's hallmark,
>> you can't guarantee that any given function won't raise
>> an arbitrary exception.

> One of my puzzlements about Java 10 years ago or so was
> why it decided to go the "must declare every exception" route.

> Consider this simple and naive numeric integrator

> def integrate(f, start, end, n):
>    delta = (end-start)/float(n)
>    x = start + delta / 2
>    sum = 0.0
>    for i in range(n+1):
>      sum = sum + f(x)
>      x += delta
>    return sum / (n+1)

> That function cannot define all the exceptions that can be
> raised because f itself can raise an arbitrary exception.  Eg,

[ cool example of f reading data from a file-system cache snipped ]

> Again, IOError might be considered a system-level error
> such that it doesn't need declaring.  Then change it to
> polling some URL ("http://cache.server/" + str(x)) when the
> network is down, or getting it from some SQL database when
> the password is incorrect, or anything else that cannot be
> determined until actually calling f().

And what if f has its own run-time plug-in mechanism?

> It looks like the only thing to do is convert all such
> unhandled exceptions and wrap them in a catch-all generic
> exception.  I think I've seen people do that.  But if so,
> what's the point of having typed exceptions?

IMO (and maybe I'm just restating the obvious; it wouldn't be the first
time <g>), "the list of exceptions f is allowed to raise" shouldn't be
part of the interface of integrate, but rather "the list of exceptions
integrate will handle gracefully" should be.  Resumably, the caller of
f, or some entity far enough up the call chain, anyway, knows something
about f that integrate does not.  In some cases, that entity could be a
human sitting at an interactive console, and that human would like to
know if/when f raises exceptions not handled by integrate.

As to the original question, I agree:  there's no way that integrate can
know every exception f might raise, and there's no reason it should,
either.  f *must be content* with handling what it promises to handle
and letting everything else pass through it unchanged.  Logically, f is
part of the *caller* of integrate rather than being among the functions
integrate *calls*.

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>
Never play leapfrog with a unicorn.



More information about the Python-list mailing list