Re: an idea: "letter bombs"

Bennett Todd (bet@std.sbi.com)
Thu, 16 Dec 1993 13:25:00 -0500 (EST)

>Example:
>
> filename = attempt(sys.argv[1], IndexError)
> if isbomb(filename):
> print 'usage: cat filename'
> sys.exit(2)
> f = attempt(open(filename, 'r'), IOError)
> if isbomb(f):
> print filename + ': cannot open:', filename.exc_value
> sys.exit(1)
> print f.read(),

It may be that I'm not seeing something from lack of relevant experience; I
haven't yet gotten up to speed on Python programming (lack of time, <whine>).
However, I don't feel like this is a good motivating example. I'd rather see
this particular example coded:

if len(sys.argv) != 1:
print 'usage:', sys.argv[0], 'filename'
sys.exit(2)
f = open(sys.argv[1], 'r')
print f.read,

I.e. I'd rather code a test that is concerned with the length of the command
line explicitly. Note that the attempt/isbomb allows more than one argument,
where subsequent args will be ignored. If the arg isn't going to be used I'd
rather emit a syntax error and let the user know. And since the default
behavior of an open() invocation is to emit an error message and die, I'd
rather leave the code uncluttered. If, for a final production delivery, you
want to have the error message look more like a traditional Unix message, I
guess I'd wrap the whole program in a try/except pair that catches errors
and formats a suitable message. In fact, I'd probably write (and use in
every program) a routine to take the exception stack trace info, extract a
short expression of where the error occurred, and print a message, probably
like

cat: open error on filename: no such file or directory

or thereabouts. If the open() invocation were down in a subroutine, I'd
be tempted to put the list of subroutine names, separated by ``:'', after
the program name, as a highly-abbreviated stack trace.

Anyway, back to your proposal, I am failing to see a useful definition of
``Expected error''. For things like end-of-file, the ``expected error''
really just means you want out-of-band signaling --- which is in fact what
you use for EOF. If something raises an exception, it should be (as I
understand it) because things have gone wrong, and the best default behavior
is to stop now, with a detailed explanation.

If I've just missed the point here, could you please tell me what's wrong
with my approach to handling the above example, or else give an example that
is more comfortable with attempt/isbomb than with try/except?

-Bennett
bet@sbi.com