How to catch a no parse exception from the read function in Haskell?

You don’t want to. You want to use reads instead, possibly like that:

maybeRead = fmap fst . listToMaybe . reads

(though you might want to error out if the second element of the tuple is not "", that is, if there’s a remaining string, too)

The reason why you want to use reads instead of catching error exceptions is that exceptions in pure code are evil, because it’s very easy to attempt to catch them in the wrong place: Note that they only fly when they are forced, not before. Locating where that is can be a non-trivial exercise. That’s (one of the reasons) why Haskell programmers like to keep their code total, that is, terminating and exception-free.

You might want to have a look at a proper parsing framework (e.g. parsec) and haskeline, too.

Leave a Comment