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:


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 (
  /*in*/ int32_t n,         /*in*/ int32_t max_depth,
  /*in*/ int32_t max_value, /*in*/ int32_t depth ) 
throw ( 
  ::ExceptionTest::NegativeValueException, 
  ::ExceptionTest::FibException
){
  // DO-NOT-DELETE splicer.begin(ExceptionTest.Fib.getFib)
  if (n < 0) {
    NegativeValueException ex = NegativeValueException::_create();
    ex.setNote("n negative");
    ex.add(__FILE__, __LINE__, "ExceptionTest::Fib_impl::getFib");
    throw ex;
  }
  // several lines delete
  // DO-NOT-DELETE splicer.end(ExceptionTest.Fib.getFib)
}





babel-0.10.2
users_guide Last Modified 2005-03-23

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