[Tutor] Program review

Ricardo Aráoz ricaraoz at gmail.com
Sun Jan 6 16:20:15 CET 2008


Kent Johnson wrote:
> Ricardo Aráoz wrote:
>> Jeff Younker wrote:
> 
>>> The enclosing try block isn't needed.  More on this later.
> 
>> Maybe it is my poor understanding of exception handling. My intention
>> here is to open the first file, if error then report in logging and
>> finish normally, else open the 2nd file, if error then report in logging
>> close the 1st file and finish normally. If no error then process.
> 
> The code is correct for what you want to do. It does seem a bit awkward 
> but it's hard to get much better and preserve the logging.
> 

Yes, I guessed so.

> You could use 'return' instead of 'raise' and eliminate the outer try block.
> 
> You could put the duplicate code in a function (with raise):
> def my_open(f):
>      try :
>          fIncl = open(f)
>      except Exception, e :
>          logging.error('Error!!! No pude abrir "%s" : %s',
>                          f,
>                          e.strerror)
>          raise
> 
> but you would still need try/except in the calling function:
> 
> try :
>      fIncl = my_open(mensaje.direcciones)
> except:
>      return
> try :
>      fExcl = my_open(mensaje.excluidas)
> except:
>      fIncl.close()
>      return
> 

AND the code would have an added depth that gives me no real benefit,
which is why I chose to do it that way. So long as meaning is not
obscured by complicated or lengthy code I'd rather keep it shallow.


> It is safe to omit the close() in this situation - the file will be 
> closed by the OS when the program terminates - so you could use a single 
> try block:
> try :
>      fIncl = my_open(mensaje.direcciones)
>      fExcl = my_open(mensaje.excluidas)
> except:
>      return

True, I usually prefer to explicitly close the file anyway.


More information about the Tutor mailing list