It Seemed Like a Good Idea at the Time Coding, Mostly

18Jul/091

Haskell Exceptions

Haskell's absolute worst feature, in my opinion, is its system of exceptions. I have yet to see a single use of exceptions that wouldn't be better served by the use of a "Maybe" or an "Either" type. Luckily, in a small nod to sanity, Haskell provides 'Control.Exception.Base.try', which returns an Either type, with the exception left, and the value right.

Once you have that, it becomes easy to implement some sane functionality for exception handling, such as my current favorite functions, defaultOnError and errorToMaybe:

defaultOnError :: a -> IO a -> IO a
defaultOnError d a = do tryValue <- try a
                        case tryValue of
                             Left  _ -> return d
                             Right v -> return v
errorToMaybe :: IO a -> IO (Maybe a)
errorToMaybe a = do tryValue <- try a
                    case tryValue of
                         Left  _ -> return $ Nothing
                         Right v -> return $ Just v
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Comments (1) Trackbacks (0)
  1. My best guess on why we have exceptions:

    You can’t catch undefined, and if you want to avoid using both that and other exceptions, you’re going to have some trouble with computations getting wrapped in increasingly complex layers of Maybe and Either in your pure code, where you may not necessarily want to handle them yet. Exceptions are a little bit more implicit (like undefined) but can still be handled by code as they propagate through the IO part of the program. In addition, instances of exception can carry information that can be quite helpful at times, like on what line and column an unexpected symbol was found.


Leave a comment


No trackbacks yet.