[Haskell-cafe] Exception handling when using STUArray

Don Stewart dons at galois.com
Sun Mar 9 14:49:36 EDT 2008


donn:
> 
> On Mar 8, 2008, at 10:54 PM, Don Stewart wrote:
> 
> [... replying to my poorly informed rant about exceptions ... ]
> 
> >
> >I don't understand this complaint -- you can handle all these with  
> >Control.Exception.
> >
> >xmonad catches all these things for example, in user code, to prevent
> >poorly written modules throwing a pattern match exception, or calling
> >'error' and making the window manager unstable.
> >
> >Handling exceptions generated from pure code is just another part of
> >making systems more robust -- and of course you can do it in Haskell.
> 
> OK, I tried this out and found that it does work, and I thought to  
> myself,
> `no more posting rants to haskell-cafe after late nights out with too  
> much
> wine!'  But then I changed my test error from a pattern match, to a  
> `head',
> and that gets past my exception handler:
> 
> 	module Main (main) where
> 	import System (getArgs)
> 
> 	ax = getArgs >>= print . head
> 
> 	px = catch ax (\ e -> putStrLn ("caught this one: " ++ show e))
> 
> 	main = px
> 
> Is there a way to catch it, that I'm missing?  What is the essential
> difference between these errors?

That's the difference between Prelude.catch and Control.Exception.catch.
You almost always want Control.Exception.catch.

Prelude.catch:

    $ runhaskell A.hs
    "A.hs: Prelude.head: empty list

Control.Exception.catch

    $ runhaskell A.hs
    "caught this one: Prelude.head: empty list

As the docs for Control.Exception say:

    -- Note that 'catch' catches all types of exceptions, and is generally
    -- used for \"cleaning up\" before passing on the exception using
    -- 'throwIO'.

    -- Also note that the "Prelude" also exports a function called
    -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
    -- except that the "Prelude" version only catches the IO and user
    -- families of exceptions (as required by Haskell 98).  
    --
    -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
    -- when importing "Control.Exception"

There's a number of other useful exception handlers:

    handle
    finally
    bracket

All useful, all have their place.

-- Don


More information about the Haskell-Cafe mailing list