try...except...finally problem in Python 2.5

Robert Kern robert.kern at gmail.com
Wed Feb 14 14:49:26 EST 2007


redawgts wrote:
> I keep getting this error "local variable 'f' referenced before
> assignment" in the finally block when I run the following code.
> 
>         try:
>             f = file(self.filename, 'rb')
>             f.seek(DATA_OFFSET)
>             self.__data = f.read(DATA_SIZE)
>             self.isDataLoaded = True
>         except:
>             self.isDataLoaded = False
>         finally:
>             f.close()
> 
> Can someone tell me what's wrong with the code? Am I doing something
> wrong? I'm somewhat new to python but this makes sense to me.

Move the "f = file(self.filename, 'rb')" above the try:. If opening the file
happens to throw an exception, then the assignment will never happen and there
will be no 'f' to close.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list