Re: What to put in the try-block
On Feb 8, 10:15 am, Kira Yamato <kira...@earthlink.net> wrote:
On 2008-02-08 03:50:51 -0500, James Kanze <james.ka...@gmail.com> said:
[...]
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.
Interesting. I would think exception handling codes are about the
exceptions to the normal flow of logic. Hence I would move it out of
the code logic. In another word, try to keep the try blocks as large
as possible.
Further, keep the try blocks as small as possible would likely cost a
run-speed penalty for setting up the try-blocks so often.
I should have been clearer. In general, of course, the reason
you report errors with an exception, and not with a return code,
is because you don't expect them to be handled immediately. The
exception should propagate up to a much higher level. In that
sense, the try block is about as far as you can get from the
code which generated the error.
The way I understood the question, however, is that there was a
need for a catch block before leaving the immediate context, in
order to do some cleaning up. In such cases, supposing that a
catch block really is necessary (because in general, I find it
preferable to handle the clean up with destructors), the try
block should be as small as possible, so that it is clear
exactly what is being cleaned up, or what we are cleaning up
from.
-- If a variable will not meet the required invariants in the
catch clause, or after, its definition belongs in the try
block.
Can you clarify a bit what you mean by "invariants in the
catch clause?"
The classical case is a constructor which fails. In that case,
of course, the declaration must be in the try block, or the
exception won't get caught. But you can imagine similar
situations:
SomeType* p ;
try {
p = new SomeType ; // may throw...
// ...
} catch ( ... ) {
// ...
}
In a case like this, the definition of p should obviously be in
the try block.
There are doubtlessly other cases, which are less obvious.
--
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