How do I catch read exceptions in Haskell?
haskell, try-catch
Solution
Use the `reads` function, which is total, and wrap the failure case as a `Maybe`, like so:
maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
`maybeRead` is quite a versatile way to do safe parsing.
Problem
In the following Haskell code: ``` data Cmd = CmdExit | CmdOther deriving (Read, Show) guiString2Cmd s = (return (read s :: Cmd)) `catch` \(e :: SomeException) -> return CmdExit ``` If I do: ``` guiString2Cmd "CmdOther" ``` it all works fine. However if I do: ``` guiString2Cmd "some wrong string" ``` the code crashes instead of evaluating to CmdExit. How can I make the code handle the exception instead of crashing?