[Tutor] constructors
alan.gauld@bt.com
alan.gauld@bt.com
Sun, 14 Apr 2002 22:28:00 +0100
> On Friday, April 12, 2002, at 08:59 AM, alan.gauld@bt.com wrote:
> > The only snag is that sometimes you can lose context
> > which makes it harder to recover from an exception
> I'm not sure I understand what you mean? How can I avoid
> this snag (or rather, what is this snag)?
What I mean is that if the try/except encompasses many
statements when an exception occurs you jump to the
end of that block with no way back in (I've always thought
a 'continue' for exception handlers would be nice!)
Thus if you are reading through a list or file and some
relatively unimportant error(divide by zero say) occurs
throwing an exception you cannot just go back to reading
your list/file. The context has been lost...
With explicit error testing on each call you only fail
the one bit in the middle of the block, you can still
go back to the start.
You can do this with exceptions too by using very small,
tightly controlled try/excepts - down to each single
statement if needed - but it then spoils the improved
readability of the code. The trick is to make the
enclosed block 'atomic', that is it only does one thing,
with no unrelated bits of code. So in my example above:
try:
for line in file.xreadlines():
processData(line)
except DivideByZero: # want to just move on to next line but...
continue # can't do this, we lost the loop context!
except IOError:
print 'File error'
So we have to do this;
try: # enclose file handling bits, catching those exceptions
for line in file.xreadlines():
try: # now enclose the data processing bits
processData(line)
except DivideByZero:
continue # still have the file/loop context
except IOError:
print 'File error'
Which looks less elegant but maintains context.
HTH,
Alan G