mb14
mb14

Reputation: 22596

How to catch read error in Haskell

I have the following problem, I'm parsing a file a use read to convert Int to String. The problem is when it fails, I have no way to display the string which fails to be parsed. I just get Exception: Prelude.read : no parse.

I tried to write my own myRead function which will use read and throw a more meaningful message but I don't know how to catch the error thrown by read.

Alternatively, is there any other way to find what's not been read properly (using debugger or trace ?)

Upvotes: 1

Views: 1080

Answers (1)

chi
chi

Reputation: 116139

case reads yourString of
  [(x,"")] -> correctlyParsed x
  _        -> errorHandling

otherwise, you can use readMaybe :: Read a => String -> Maybe a as follows

import Text.Read

case readMaybe yourString of
  Just x  -> correctlyParsed x
  Nothing -> errorHandling

Upvotes: 8

Related Questions