next up previous contents index
Next: Invoking Babel to generate Up: C++ Binding Previous: Calling Methods from C++   Contents   Index


Catching and Throwing Exceptions in C++

Adapted from the Babel regression tests, the following is an example of a package called ExceptionTest that has a class named Fib with a method declared in SIDL as follows:


int getFib(in int n, in int max_depth, in int max_value, in int depth)
  throws NegativeValueException, FibException;

The corresponding C++ code fragment to use this method is:


#ifdef SIDL_USE_UCXX
using namespace ucxx;
#endif

ExceptionTest::Fib fib = ExceptionTest::Fib::_create();
try { 
  int result = fib.getFib( 4, 100, 32000, 0 );
  cout << "Result of fib.getFib() = " << result << endl;
} catch ( ExceptionTest::NegativeValueException  e ) { 
  // ...
} catch ( ExceptionTest::FibException e ) { 
  // ...
}

This example shows the standard way to throw an exception in C++. You are not strictly required to call the setNote and add methods; however, these methods provide information that may be helpful in debugging or error reporting.


int32_t
ExceptionTest::Fib_impl::getFib_impl (
  /*in*/ int32_t n,         
  /*in*/ int32_t max_depth,
  /*in*/ int32_t max_value, 
  /*in*/ int32_t depth ) 
throw (
  UCXX ::ExceptionTest::FibException,
  UCXX ::ExceptionTest::NegativeValueException,
  UCXX ::sidl::RuntimeException
){
  // DO-NOT-DELETE splicer.begin(ExceptionTest.Fib.getFib)
  if (n < 0) {
    UCXX ::ExceptionTest::NegativeValueException ex = 
      UCXX ::ExceptionTest::NegativeValueException::_create();
    ex.setNote("n negative");
    ex.add(__FILE__, __LINE__, "ExceptionTest::Fib_impl::getFib");
    throw ex;
                                                                                
  } else if (depth > max_depth) {
    UCXX ::ExceptionTest::TooDeepException ex =
      UCXX ::ExceptionTest::TooDeepException::_create();
    ex.setNote("too deep");
    ex.add(__FILE__, __LINE__, "ExceptionTest::Fib_impl::getFib");
    throw ex;
                                                                                
  } else if (n == 0) {
    return 1;
                                                                                
  } else if (n == 1) {
    return 1;
                                                                                
  } else {
    int32_t a = getFib(n-1, max_depth, max_value, depth+1);
    int32_t b = getFib(n-2, max_depth, max_value, depth+1);
    if (a + b > max_value) {
      UCXX ::ExceptionTest::TooBigException ex = 
	UCXX ::ExceptionTest::TooBigException::_create();
      ex.setNote("too big");
      ex.add(__FILE__, __LINE__, "ExceptionTest::Fib_impl::getFib");
      throw ex;
    }
    return a + b;
  }
  // DO-NOT-DELETE splicer.end(ExceptionTest.Fib.getFib)
}
                                                                                





babel-0.99.0
users_guide Last Modified 2006-06-27

http://www.llnl.gov/CASC/components
components@llnl.gov