[Haskell-beginners] Re: how to read file with locking

Ertugrul Soeylemez es at ertes.de
Mon Oct 11 01:35:25 EDT 2010


Jimmy Wylie <jwylie at uno.edu> wrote:

> > It is, BTW, always preferable to use withFile over openFile, if you can.
> > This makes your code cleaner and also exception-safe.
>
>      I don't think I quite understand. How is withFile exception-safe? 
> Under the covers it's using openFile. I was under the impression 
> withFile was just a nice way to remove boilerplate file operation code.  
> Here's what I found on hoogle: "withFile 
> <http://haskell.org/hoogle/?hoogle=withFile> name mode act opens a file 
> using openFile <http://haskell.org/hoogle/?hoogle=openFile> and passes 
> the resulting handle to the computation act. The handle will be closed 
> on exit from withFile <http://haskell.org/hoogle/?hoogle=withFile>, 
> whether by normal termination or by raising an exception."

The last statement is the point:

  "[...] whether by normal termination or by raising an exception."

If you openFile and hClose manually, then you need to take care of
exceptions yourself.  You need to make sure that hClose is called in all
cases.  For example, what if reading the file throws an exception, which
is not catched?  hClose may be skipped that way.  withFile ensures that
the handle is always closed, even if an exception escapes your function.


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/




More information about the Beginners mailing list