Solution to integrate(f) raises ??? (Re: How do I know all thrown exceptions of a function)?

Greg Ewing greg at cosc.canterbury.ac.nz
Tue Jan 23 19:53:15 EST 2001


Andrew Dalke wrote:
> 
> 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?

I have an answer to this! It requires the language to have
nested procedures, and to allow passing of nested procedures
as parameters (a la Pascal). Then, by introducing the rule:

  * If a procedure raises an exception which is not declared
    in that procedure's signature, it propagates _lexically_
    outwards to a procedure which does declare it.

Here's an example using a hypothetical pseudo-Pascal which
has exception handling:

-----

function integrate(function f(x: real): real; lo,hi: real): real
  raises MathError;
begin
...
end;

function lookup_cache(x: real; var y: real): boolean
  raises DiskError;
begin
...
end;

function integrate_g: real
  raises MathError, DiskError;

  function g(x: real): real 
    raises MathError;
  var 
    y: real;
  begin
    if not lookup_cache(x, y) then {any DiskError raised in here will
propagate}
      y := do_evaluation(x);       {out to integrate_g}
    g := y;
  end;

begin
  integrate(g, 0.0, 1.0);
end;

procedure main;
begin
  try
    integrate_g;
  except MathError do
    writeln('Math error!');
  except DiskError do
    writeln('Disk error!');
  end;
end;

-----

As you can see, this allows you to declare integrate() in the
natural way, while not restricting in any way what exceptions
can be raised in the function being integrated. In g(), it's
legal to call lookup_cache() which can raise DiskError, even
though g() doesn't declare it, because g() is nested inside
another function which does declare it.

How to apply this to Python? It would have to wait until we
have nested lexical scoping. Then, when an exception is raised,
it should be a simple matter to search up the static chain for
the frame of a function which has declared that it's willing to
raise that exception, and propagate it dynamically from there
to its caller. Do the same for the caller, etc., until baked.

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list