Re: throwing exceptions from constructor and other alternatives
I don't know, I have mixed fillings now. Many people is saying that
throwing from constructor is totally normal, however how do you think
the resulting syntax will look like?
try{
object construtor
use of object
}catch(...){
object construtor with alternative values
SAME use of object
}
If you go with the throwing constructor, I would suggest the following:
#include <boost/optional.hpp>
boost::optional<root_finder> opt_finder;
try
{
opt_finder = root_finder(f, lb, ub);
}
catch (root_finder::bracket_too_narrow&)
{
opt_finder = root_finder(f, lb - 1.f, ub + 1.f); // will throw if
still not wide enough
}
// use opt_finder
Note particularly that the try block is as small as possible and the
catch block only catches the exception we're expecting.
(Side-note: even if root_finder is not copyable for some reason,
boost::optional provides a factory creation mechanism to cope with
that)
Particularly in C++, exceptions aren't pretty when they're used to deal
with expected conditions as above.
Another idea would be for root_finder to provide a static function that
evaluates whether a set of parameters is valid:
if (!root_finder::parameters_valid(f, lb, ub))
{
lb -= 1.f;
ub += 1.f;
}
root_finder rf(f, lb, ub); // will throw if bracket still not wide
enough
// use rf
The constructor could call parameters_valid internally.
James
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]