Handling Errors

Simon Marlow simonmar at microsoft.com
Fri Apr 25 11:51:55 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

Slight correction: the right library to use is Control.Exception:

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

GHC.Exception is not indended for external consumption, as is the case with all the GHC.* libraries except for GHC.Exts - the clue
is "Stability: internal" in the header.  We should really omit these from the docs.

> 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.

In cases like the above, you almost certainly want to use withCString which also guarantees to free the string if an exception is
raised.

Cheers,
	Simon




More information about the FFI mailing list