Identifying exceptions that can be raised

Andrew Dalke adalke at mindspring.com
Sat Nov 20 02:18:32 EST 2004


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,

def f1(x):
   return 1/max(5-x, 0))  # Can raise a divide-by-zero error

integrate(f1, 0, 10, 5)

Java handles that case by saying you don't need to declare
system exceptions.  Then consider

def f2(x):
   fname = os.path.join("/cache/directory", str(x))
   if os.path.exists(fname):
     return float(open(fname, "r").read())
   y = _f2(x)
   outfile = open(fname, "w")
   try:
     outfile.write(str(y))
   finally:
     outfile.close()
   return y

integrate(f2, 0, 10, 10)

If the file is not readable, or the directory not readable,
then this might raise an IOError.

How does the 'integrate' function declare that it can raise
any of the errors that the integrator function 'f' might raise?

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().

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?

Curiously-y'rs,

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list