Catching thrown exceptions

This example illustrates the use of C++ exception handling to compute a sample version of the library function Hypotenuse, the root sum of the squares of its two arguments. A numerically stable formula is , where max and min are the larger and smaller, respectively, of the absolute values of the two arguments. But the formula breaks down if both arguments are zero or infinite. SampleHypotenuse catches the invalid exception that arises from or and performs the simple fix.

      #pragma fenv_access on
      double SampleHypotenuse(double x, double y) { // May be called with any rounding.
          TFPEnvironmentSaveAndUpdate localEnvironment;
          double_t min = Min(Abs(x), Abs(y));
          double_t max = Max(Abs(x), Abs(y));
          try {
              
    TFPExceptionHandler invalidHandler(kFPInvalid);
              return max * SquareRoot(1.0 + Square(min / max));
          }
          
    catch (const TFPInvalidException& caughtInvalid) {
              localEnvironment.ClearFlags(kFPInvalid); // clear spurious exception
              return max; // two zeroes or two infinities
          }
      }
The class TFPExceptionHandler creates TFPException objects and throws C++ exceptions. Its constructor:

  1. Saves the current environment
  2. Records the TFPExceptionSet argument indicating which exceptions are to be thrown
Its destructor:

  1. Checks to see if one of the exceptions to be thrown has been raised
  2. Merges the flags saved by the constructor into the current environment
  3. Throws the exception of highest precedence detected in Step 1, if any
This code uses TFPEnvironmentSaveAndUpdate, so it passes raised flags back to its caller:

SampleHypotenuse is accurate across the entire range of arguments. It honors the direction of rounding modes in the sense that SampleHypotenuse(x, y) is no greater than when rounding toward zero or toward , and is no less when rounding toward .


[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker