Handling Errors

Alastair Reid alastair at reid-consulting-uk.ltd.uk
Thu Apr 24 12:02:26 EDT 2003


> The question is, if newCString fails to get allocation to s1 or s2,
> how must i handle this error?. 

Using the normal Haskell98 IOError mechanisms:

  http://www.haskell.org/onlinereport/io-13.html

More usefully, you can use the GHC extensions (also supported by Hugs):

  http://www.haskell.org/ghc/docs/latest/html/base/GHC.Exception.html

of which the most useful are bracket and bracket_ which provide
functionality like Java/C++'s try/finally syntax.

  bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
  bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c

e.g., 

main = bracket (newCString s1) free $ \p1 ->
       bracket (newCString s2) free $ \p2 ->
       let p3 = hstrL p2 p1
       in peekCString p3 >>= \s ->
          print s

This code will take care to free the two strings even if an exception is
raised.

--
Alastair Reid                 alastair at reid-consulting-uk.ltd.uk  
Reid Consulting (UK) Limited  http://www.reid-consulting-uk.ltd.uk/alastair/



More information about the FFI mailing list