[Rcpp-devel] idiom for creating an informative message for an exception

Romain Francois romain at r-enthusiasts.com
Thu Dec 2 22:46:15 CET 2010


Le 02/12/10 22:15, Douglas Bates a écrit :
> In the lme4a package I mixed calls to Rf_error and throwing C++
> exceptions.  This is causing problems and I plan to replace the calls
> to Rf_error by exceptions so that there is a consistent approach.
>
> Many of the calls to Rf_error take advantage of the fact the Rf_error
> implicitly calls sprintf to create the error message.  Thus I have
> calls like
>
> 	if (!d_x.size() == d_nrow * d_ncol)
> 	    ::Rf_error("%s: Dim = (%d, %d) is inconsistent with x.size() = %d",
> 		       "ddenseMatrix::ddenseMatrix", d_nrow, d_ncol, d_x.size());
>
> Is there a similar idiom for creating an exception's "what" argument?
> I imagine I could add std::strings and maybe use some iostreams or
> something like that ...

Maybe you can use sprintf, e.g :


require( inline )
require( Rcpp )

fx <- cxxfunction( , '

     // replace 100 by whatever is large enough
     // the backslashes below are just because of R escaping
     std::string message( 100, \' \' ) ;
     sprintf( const_cast<char*>(message.data()), "%s %d", "bla bla", 2 ) ;
     return wrap( message ) ;

', plugin = "Rcpp" )


you could for example use sprintf in the body of the constructor of your 
exception class.

Romain

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/hovakS : RcppGSL initial release
|- http://bit.ly/iaxTdO : parser 0.0-12
`- http://bit.ly/gnCl01 : Rcpp 0.8.9




More information about the Rcpp-devel mailing list