Re: Exceptions, Go to Hell!
On Aug 24, 5:12 pm, tni <t...@example.invalid> wrote:
On 2010-08-24 14:32, Goran Pusic wrote:
That's quite alright, except that it's not really nice to abort on
bad_alloc in particular. That's almost always too harsh.
It's only OK if the whole program is one "do work" iteration, and even
then, it cost little to write one catch in main(), e.g.
int main()
{
try { return work(); }
catch(const exception& e) // perhaps bad_alloc, perhaps somet=
hing
else.
{ return error_code_from_exception(); /*nothrow guarantee here*/=
}
}
Goran.
That only works if you write exception safe code. If you don't (and I
have the distinct impression the OP doesn't want to), you want to abort.
Heh, that's very true. However, aborting is a massively substandard
coding (to me at least, and especially in C++, where language
capabilities - think RAII - make any recovery a breeze). And e.g. no
library code should ever do it, 'cause it's not library writer's
choice to make.
On top of that, both exceptions and premature returns require similar
approach to coding. Premature return is effectively very simple coding
strategy, e.g. (using ScopeGuard and counting absence of any other
resource handling class):
RESULT_TYPE f(params)
{
RESOURCE_TYPE1 r1 = alloc1();
ON_BLOCK_EXIT(free, r1);
// rinse, repeat this, add more resources
RESULT_TYPE r = call1(params);
if (failed(r))
{
assert(0);
return r;
}
// By the way, you can wrap 6 lines above in a macro, so you get
e.g.
// CHECKED(RESULT_TYPE, call1(params));
RESOURCE_TYPE2 r2 = alloc2();
ON_BLOCK_EXIT(free, r2);
...
return RESULT_TYPE(SUCCESS);
// Any resources freed automaticaly by scope guards
}
(It's similarly simple if some resource(s) should be a e.g. return
value or kept for later in some global state, but then one would use a
Make(Obj)Guard and "Dismiss").
All in all, exceptions or not, in C++, code that is exception safe is
also __extremely__ simple in form, and works correctly even if you put
exceptions out of the picture.
If you have an OS that overcommits memory, you very likely won't get a
bad_alloc anyway.
Yes. BTW, I hate overcommit, because large swaths of people have
experienced it and now think that handling memory correctly is
effectively futile. But that's not how C, C++, nor many other a-
language, is meant to work, not at all.
Goran.