I am sorry MrAsm, but under no circumstances can you use this sample code.
On Wed, 30 May 2007 16:35:50 -0500, "Doug Harrison [MVP]"
<dsh@mvps.org> wrote:
If he wanted to perform the conversion and handle the error on the spot,
I
think he'd be better off using strtod, strtol, or strtoul, and I linked
to
messages describing their use in my first reply.
What I'm getting at is that it's a misuse of exceptions to litter your
code
with:
try
{
int x = lexical_cast<int>(s);
}
catch (bad_lexical_cast)
{
whatever;
}
It's much better to use one of the aforementioned functions and just test
return codes. The exception approach makes sense if you are not handling
the error locally but someplace upwards in the call chain.
I don't agree.
It's easier and more elegant (IMHO) to use a single catch (
bad_lexical_cast & ) than process all the possible error codes of
strtod (and similar functions):
<strtod return value>
The strtod() function returns the converted value, if there is any. If
no conversion could be performed, strtod() returns zero. If the
correct value is outside the range of representable values (plus or
minus), strtod() returns HUGE_VAL (according to the sign of the value)
and sets errno to ERANGE. If the correct value causes underflow,
strtod() returns zero and sets errno to ERANGE.
</strtod return value>
vs.
just a catch( bad_lexical_cast & ).
And I see no problem in locally catching the exception and not
propagate it upwards the call chain.
This is the code sample from Boost lexical cast page:
<CODE url="http://www.boost.org/libs/conversion/lexical_cast.htm">
int main(int argc, char * argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
std::vector<short> args;
while(*++argv)
{
try
{
args.push_back(lexical_cast<short>(*argv));
}
catch(bad_lexical_cast &)
{
args.push_back(0);
}
}
...
}
</CODE>
They are just doing the catch locally, as I intended.
I think it's better than doing several if for strtod error conditions.
MrAsm