Haskell: Dealing With Types And Exceptions

Posted by Douglas Brunner on Stack Overflow See other posts from Stack Overflow or by Douglas Brunner
Published on 2010-04-21T12:36:54Z Indexed on 2010/04/21 12:43 UTC
Read the original article Hit count: 196

Filed under:
|
|

I'd like to know the "Haskell way" to catch and handle exceptions. As shown below, I understand the basic syntax, but I'm not sure how to deal with the type system in this situation.

The below code attempts to return the value of the requested environment variable. Obviously if that variable isn't there I want to catch the exception and return Nothing.

getEnvVar x = do {
    var <- getEnv x;
    Just var;
} `catch` \ex -> do {
    Nothing
}

Here is the error:

Couldn't match expected type `IO a'
       against inferred type `Maybe String'
In the expression: Just var
In the first argument of `catch', namely
    `do { var <- getEnv x;
          Just var }'
In the expression:
      do { var <- getEnv x;
           Just var }
    `catch`
      \ ex -> do { Nothing }

I could return string values:

getRequestURI x = do {
    requestURI <- getEnv x;
    return requestURI;
} `catch` \ex -> do {
    return ""
}

however, this doesn't feel like the Haskell way. What is the Haskell way?

© Stack Overflow or respective owner

Related posts about haskell

Related posts about exception