Granularity of OSError
no.email at please.post
Fri Sep 18 20:54:56 CEST 2009
I've often come across the idea that good Python style deals with
potential errors using an EAFP ("easier to ask forgiveness than
permission") strategy rather than a LBYL ("look before you leap")
For example, LBYL would look like this:
In contrast, EAFP would look like this:
But, as written, the EAFP code above is not satisfactory, because
there can be OSError's triggered for reasons other than the
non-existence of the regular file some_file.
What one needs is a finer granularity of exception, mapping to
exactly the error that one is guarding against.
Is there a standard approach to refining the granularity of exceptions
such as OSError? The only approach I can think of is to somehow
parse the error string (assuming is available) to determine whether
the exception is indeed of the specific kind we're trying to catch.
But this strikes me as grossly inelegant. Is there a better way?
(BTW, the problem is generic, because client code has no control
over the specificity of the exceptions raised by a library module.
If these exceptions turn out to be too broad, client code has to
somehow deal with this reality, at least in the short term.)
More information about the Python-list