Close as Many Files/External resourcs as possible in the face of exceptions

Mel Wilson mwilson at the-wire.com
Mon Nov 21 07:09:11 EST 2011


GZ wrote:
> Here is my situation. A parent object owns a list of files (or other
> objects with a close() method). The close() method can sometimes 
fail
> and raise an exception. When the parent object's close() method is
> called, it needs to close down as many files it owns as possible, 
even
> if the close() function of some files fail. I also want to re-raise 
at
> least one of the original exceptions so that the outer program can
> handle it.
[ ... ]
> 
> It will re-raise the first exception and preserve the context and
> close as many other files as possible while ignoring any further
> exceptions.
> 
> But this looks really awkward. And in the case that two files fail 
to
> close, I am not sure the best strategy is to ignore the second
> failure.

I imagine you could save any caught exception instances in a list and 
study them later.

	Mel.




More information about the Python-list mailing list