[Q] Are Exceptions used that much in practice?
greg at cosc.canterbury.ac.nz
Tue Dec 12 22:50:35 EST 2000
Alex Martelli wrote:
> def setattr_ok(obj, attr, value):
> try: setattr(obj, attr, value)
> except (AttributeError, ValueError): return 0
> else: return 1
There are dangers in that approach when the exception
being caught is a very common one such as AttributeError.
If the obj is such that calling setattr on it causes some
Python code to be executed, and there is a bug in that
code which causes an AttributeError to be raised, you'll
never know about it.
A similar problem occurs with Python's use of IndexError
to terminate a for-loop.
For that reason, I have mixed feelings about whether
the exception-as-normal-flow-control style of programming
is a good idea. It might be okay if you use a special-purpose
exception class created just for that particular use,
but abusing exceptions which normally indicate bugs is
asking for trouble, in my opinion.
> def open_if_ok2(filepath):
> try: return open(filepath, 'r')
> except IOError: return None
A minor gripe here - it would be more useful if Python
had some subclasses of IOError to distinguish between
different reasons for failure, so you can catch them
more selectively. If the reason is "the file doesn't
exist", you might want to do something to make it exist
and then try again. But if the reason is "the file exists
but the user doesn't have permission" or "someone put
peanut butter in the disk drive", you probably just want
to let the exception propagate.
Greg Ewing, Computer Science Dept, University of Canterbury,
Christchurch, New Zealand
To get my email address, please visit my web page:
More information about the Python-list