How do I know all thrown exceptions of a function?

D-Man dsh8290 at rit.edu
Tue Jan 23 17:17:46 EST 2001


On Mon, Jan 22, 2001 at 06:33:03PM -0700, Andrew Dalke wrote:
| 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]
|   ...
| 
[snip]
| What is the best way to handle this unexpected exception in the Java
| way?

int integrate( <can't have a function-pointer anyways ;-)> func ,
	float x_min ,
	float x_max ) 
	throws Exception
{
	...
}

Is one 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
| 

Is another way.

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

I agree that it is ugly to have to declare all possible exception
types.  That's not to say you shouldn't document it, but it should be
/documented/ not forced by the /compiler/.

The C++ method isn't entirely bad (as Alex mentioned), and the new
"attributes of functions" feature in 2.1 may be extended to support
this[1].  This would allow programmatic access to the exception
documentation.

-D

[1]  I don't know if there are any real plans for it, but I see it as
     a consistent and reasonable way to add it.




More information about the Python-list mailing list