IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
6.2 Exception Handling


6.2 Exception Handling

We desired better control over exception handling than currently exists in Numeric. This has traditionally been a problem area (see the numerous posts in comp.lang.python regarding floating point exceptions, especially those by Tim Peters). Numeric raises an exception for integer computations that result in a divide by zero or multiplications that result in overflows. The exception is raised after that operation has completed on all the array elements. No exceptions are raised for floating point errors (divide by zero, overflow, underflow, and invalid results), the compiler and processor are left to their default behavior (which is usually to return Infs and NaNs as values).

The approach for numarray is to provide customizable error handling behavior. It should be possible to specify three different behaviors for each of the four error types independently. These are:

  • Ignore the error.
  • Print a warning.
  • Raise a Python exception.
The current implementation does that and has been tested successfully on Windows, Solaris, Redhat and Tru64. The implementation uses the floating point processor ``sticky status flags'' to detect errors. One can set the error mode by calling the error object's setMode method. For example:
>>> Error.setMode(all="warn") # the default mode
>>> Error.setMode(dividebyzero="raise", underflow="ignore", invalid="warn")

The Error object can also be used in a stacking manner, by using the pushMode and popMode methods rather than setMode. For example:

>>> Error.getMode()
_NumErrorMode(overflow='warn', underflow='warn', dividebyzero='warn', invalid='warn')
>>> Error.pushMode(all="raise") # get really picky...
>>> Error.getMode()
_NumErrorMode(overflow='raise', underflow='raise', dividebyzero='raise', invalid='raise')
>>> Error.popMode()  # pop and return the ``new'' mode
_NumErrorMode(overflow='raise', underflow='raise', dividebyzero='raise', invalid='raise')
>>> Error.getMode()  # verify the original mode is back
_NumErrorMode(overflow='warn', underflow='warn', dividebyzero='warn', invalid='warn')
Integer exception modes work the same way. Although integer computations do not affect the floating point status flag directly, our code checks the denominator of 0 in divisions (in much the same way Numeric does) and then performs a floating point divide by zero to set the status flag (overflows are handled similarly). So even integer exceptions use the floating point status flags indirectly.

Send comments to the NumArray community.