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, 'filename'
f = open(sys.argv, 'r')
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
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?