[Tutor] Try except really better than if?
Alan Gauld
alan.gauld at btinternet.com
Mon Jan 10 19:16:06 CET 2011
"Steven D'Aprano" <steve at pearwood.info> wrote
> Wrapping an atomic block of code, so long as it actually *can* be
> treated as atomic (including backing out any changes if it fails),
> is a good use of try...except.
That's exactly what I meant by atomic. A (smallish) group of
instructions
that must be treated as a group, if any one fails the whole block
fails
and must be backed out or aborted.
> Provided the entire try block needs to be treated as a single
> operation (in which case, why isn't it a function?)
The point about the function is good and the try/except can live
within the function.
> a single operation. That is, the individual sub-tasks should have no
> side-effects, or they must be backed out off on failure.
Absolutely. That is the key criterion.
> It has been said that error handling is ten times harder than
> handling the rest of your code.
Yep, and usually takes up about ten times as much code.
I once analyzed a largish project - about 1.5 million lines of C++.
Only ~250k lines were actual funcionality, the rest were split between
GUI (before GUI Builders etc) and error handling (and some logging
for our IT department's benefit). I can't recall the split between GUI
and errors but it was scary to see how little was real functonal
code...
( This didn't include any SQL or script files but it was before the
days
of stored procedures so most of the SQL was probably ermbedded
in the C++ anyway).
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list