exception handling in set_str functions

Marc Glisse marc.glisse at inria.fr
Tue Jun 16 07:53:08 UTC 2015


On Tue, 16 Jun 2015, Matthew Niemerg wrote:

> I am working on a project that makes use of gmp and started to do some
> simple tests with exception handling.
>
> I noticed that two functions (in mpz_class, mpq_class, mpf_class)
>
> int set_str(const char *s, int base)
>
> and
>
> int set_str(const std::string &s, int base)
>
> simply modify the internal mp object in their respective classes by
> calling the appropriate
>
> int mp*_set_str(const char *s, int base)
>
> function.
>
> The constructor methods, on the other hand, do throw exceptions when
> the string literal cannot be converted.
>
> Shouldn't these methods also perform exception handling?

For constructors and operator=, an exception is the only way to signal an 
error. set_str on the other hand returns a value that indicates if there 
was a failure, and the user has a choice on how he wants to handle it. You 
are free to throw an std::invalid_argument, it will only take you one more 
line of code, but people who don't need exceptions can avoid paying the 
cost of throwing+catching.

It would not be absurd to have a set_str_with_exception that returns void 
and throws on error, but to save 1 line of code it does not seem worth it.

-- 
Marc Glisse


More information about the gmp-discuss mailing list