|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2000-06-06 10:52:00
> > > Returning default values on failure is ambiguous, unless you
> > > know from your context that the default would be impossible.
> >
> > Agreed. But sometimes we may indeed know this:
> >
> > int n = stream_cast<int>(argv[1], 0);
> > if (n < 5)
> > {
> > std::cerr << "x must be a number greater than 4.";
> > return EXIT_FAILURE;
> > }
> >
> > Do we care whether the user typed "fred" or "3"? Possibly not.
>
> This type of error handling scenario is a poster child for exceptions.
> The exception overhead is insignificant, and it makes easy generic and
> more robust error handling. True, you don't need to tell to the user
> that the parameter wasn't even a number, but sometimes it can be nice.
> With exceptions, you can use the same code, or at least the same
> coding pattern, for problems that do and do not have the luxury of
> knowing that 0 (or whatever) is illegal and for problems that do and
> do not need verbose error reporting.
The point is that the programmer should make the decision whether a default
return value or an exception is more appropriate.
When faced with an exception-throwing stream_cast, I would be forced to
define my own
template<class T, class S> T stream_cast_def(S const & source, T const &
defaultValue = T())
{
try
{
return stream_cast<T>(source);
}
catch(stream_cast_exception const &)
{
return defaultValue;
}
}
which is, in this case, inefficient.
-- Peter Dimov Multi Media Ltd.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk