How do I know all thrown exceptions of a function?

Andrew Dalke dalke at acm.org
Mon Jan 22 20:33:03 EST 2001


Delaney, Timothy wrote:
>Personally, I think Java's view of exceptions (almost) makes
>sense.

Actually, I disagree.  Consider a function which numerically
integrates another function over a given range:

def integrate(func, x_min, x_max):
  ...
  will compute func(x) for several values of x between [x_min, x_max]
  ...

What exceptions does "integrate" throw, given that "func" can
throw anything?  As I understand the Java way, you must declare
all of the exceptions thrown by "func", which most people will
take to mean it only throws a math error (divide by zero, overflow,
etc.).  Once the "func" exceptions are known, the "integrate"
ones are also known.

However, suppose func is very involved and I decide to use a cache:

class MyCache:
  def __init__(self, func, cache_file = "func.cache"):
    # open the file as a dbm; don't know the args but this is
    self.cache = gdbm.open(cache_file, "rw")  # close enough
    self.func = func
  def __call__(self, x):
    y = self.cache.get(x)
    if y is not None:
       return y
    y = self.func(x)
    self.cache[x] = y
    return y

Suppose also that the file system breaks, or gets full, so the
dbm interface no longer works.  This throws a dbm error.  What
is the best way to handle this unexpected exception in the
Java way?

I actually don't know.  As far as I can tell, the only way to
do it is let integrate raise a specific "CannotIntegrate"
exception, then implement a wrapper, like for MyCache, which
converts any non-numeric exception in the CannotIntegrate
exception, as in

  try:
    y = self.func(x)
  except (DivideByZeroException, other expected math errors ...):
    raise
  except (SystemExit, KeyboardInterrupt):  # allow forced breaks
    raise
  except:
    .. convert to a CannotIntegrate exception ..
  return y

To me, this is ugly and error prone.  (Is this really what
you need to do for Java - the Feb. Dr. Dobb's comparison
between Java and C# suggests so.)  Thus, I would rather write
my code to be exception safe, in that it gracefully accepts
any exception, then to declare every exception type.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list