question about try/except blocks
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu May 2 23:02:34 EDT 2013
On Thu, 02 May 2013 21:54:29 -0400, J wrote:
> I have this function in a class:
>
> def write_file(self, data, dest):
> with open(dest, 'wb', 0) as outfile:
> try:
> print("IN WRITE_FILE")
> outfile.write(self.data)
> except IOError as exc:
> logging.error("Unable to write data to %s: %s", dest,
> exc) return False
> else:
> outfile.flush()
> os.fsync(outfile.fileno())
> return True
[...]
> I think, functionally, that should work, but should nested try/except
> blocks be avoided?
Not particularly. Try/except is cheap to set up, nesting them doesn't
cost much.
But having said that, your code as given does not protect against rare
but possible errors. For example, just because you can open the file for
writing doesn't mean you can write to it; just because you can write to
it doesn't mean flush will succeed; just because flush succeeds doesn't
mean that syncing to disk will succeed. Any IO operation might fail.
While you can wrap each one individually, it's probably better to wrap
the whole lot at once. I'd write it like this:
def write_file(self, data, dest):
try:
with open(dest, 'wb', 0) as outfile:
print("IN WRITE_FILE")
outfile.write(self.data)
outfile.flush()
os.fsync(outfile.fileno())
except (OSError, IOError) as exc:
logging.error("Error writing data to %s: %s", dest, exc)
return False
return True
File IO is one of the rare exceptions to the idea that try/except blocks
should wrap the least amount of code possible.
--
Steven
More information about the Python-list
mailing list