Re: What to put in the try-block
On Feb 7, 10:05 am, "Erik Wikstr=F6m" <Erik-wikst...@telia.com> wrote:
I just thought of a question that I have never seen discussed before
(perhaps it is trivial?) and while I think I know the answer I realise
that others might have other oppinions, which is why I ask it here.
How much code should one put in the try-block, i.e. if you have code
such as this:
foo;
bar;
baz;
try {
somecode;
}
catch (exception& e) {
// ...
}
and you have to posibility to also put foo, bar, and baz in the try-
block, should you do so?
I think no, since by limiting the stuff in the try-block I
more clearly indicate what might throw (or which depends on
something not throwing) than I do if I put as much as possible
in it. Are there any other oppinions or motivations?
Two guiding principles, IMNO:
-- I like to keep the try blocks as small as possible, in order
to keep the error handling code as near to the source of the
error as possible.
-- If a variable will not meet the required invariants in the
catch clause, or after, its definition belongs in the try
block.
In general, however, it's best to avoid try blocks completely,
and use destructors. Even to the point of defining a special
transaction type to handle it. And while I've not experimented
with it, I suspect that something along the lines of Andrei's
scope guard could be used to great avail here. It should be
possible to modify it to something along the lines of:
foo ;
ON_ERROR( foo cleanup ; )
bar ;
ON_ERROR( bar cleanup ; )
// ...
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34